Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
Wrap all occurences of Array<word> in string in <em></em> Javascript, allowing "em" to be a word

The usecase: I have a search input that allows users to enter space-separated words to search for in a list of entries. I want to only display matches that match any of the words provided, and highlight those parts of the entries that match.

Given this array of haystacks:

const haystacks = [
 { value: 'Hello World', visible: true }, 
 { value: 'I was here', visible: true }, 
 { value: 'tell me your name', visible: true }
];

and this array of needles

const needles = ['el', 'rl', 'em'];

how can I wrap all matching parts of the strings in <em></em>, and for those that have no match set visible: false:

// expected result
[
  { value: 'H<em>el</em>lo Wo<em>rl</em>d', visible: true }, 
  { value: 'I was here', visible: false }, 
  { value: 't<em>el</em>l me your name', visible: true }
]

I have checked How to compare string with array of words and highlight words in string that match? but that one only highlights words that fully comply with the needles, not partial matches.

Here's what I've tried, which gives me

[
  { value: "H<<em>em</em>>el</<em>em</em>>lo Wo<<em>em</em>>rl</<em>em</em>>d", visible: true },
  { value: "I was here", visible: false },
  { value: "t<<em>em</em>>el</<em>em</em>>l th<em>em</em> your name",    "visible": true }
]

const haystacks = [{ value: 'Hello World', visible: true }, { value: 'I was here', visible: true }, { value: 'tell them your name', visible: true }];

const needles = ['el', 'rl', 'em'];

for (const haystack of haystacks) {
  for (const needle of needles) {
    const isMatchingOption = haystack.value.toLowerCase().includes(needle);
    haystack.visible = isMatchingOption;
    if (isMatchingOption) {
      const re = new RegExp(needle.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'), 'gi');
      haystack.value = haystack.value.replace(re, '<em>$&</em>');
    }
  }
}

console.log(haystacks);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should aim to create only one, comprehensive regular expression, not one per needle:

const regEscape = s => s.replace(/[.*+?^${}()|[\\]/g, "\\$&");

function highlight(haystacks, needles) {
    // Sort needles by descending length (in a copy)
    needles = [...needles].sort((a, b) => b.length - a.length);
    const regex = RegExp(needles.map(regEscape).join("|"), "gi");
    return haystacks.map(({value}) => ({
       value: value.replace(regex, `<em>$&</em>`),
       visible: regex.test(value)
    }));
}

// Example run:
const haystacks = [
    { value: 'Hello World' }, 
    { value: 'I was here' }, 
    { value: 'tell me your name' }
];

const needles = ['el', 'rl', 'em'];

console.log(highlight(haystacks, needles));

The needles are sorted by descending length so that if one is a substring of the other, the longer one gets precedence for the replacement.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda