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

341
Visualizações
How to highlight text regardless whether uppercase or lowercase as long as they match in React?
import React from "react";

const Highlighter = ({
  children,
  highlight,
}: {
  children: any;
  highlight: any;
}) => {
  if (!highlight) return children;
  const regexp = new RegExp(highlight, "g");
  const matches = children.toString().match(regexp);
  var parts = children
    .toString()
    .split(new RegExp(`${highlight.replace()}`, "g"));

  for (var i = 0; i < parts.length; i++) {
    if (i !== parts.length - 1) {
      let match = matches[i];
      // While the next part is an empty string, merge the corresponding match with the current
      // match into a single <span/> to avoid consequent spans with nothing between them.
      while (parts[i + 1] === "") {
        match += matches[++i];
      }

      parts[i] = (
        <React.Fragment key={i}>
          {parts[i]}
          <span className="highlighted">{match}</span>
        </React.Fragment>
      );
    }
  }
  return <div className="highlighter">{parts}</div>;
};

export default Highlighter;

The code above are able to highlight the text as used below:

<Highlighter highlight="text">
    This is some random text
</Highlighter>

and this will result in the text being highlighted. However, if I change the highlight attribute to: highlight="Text", it wouldn't highlight the text anymore because there is an uppercase T. How do I modify this code so that it would even match lower/uppercase letter?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You will need to transform the text and the hightlight to lower case , after matching the word use the index of the matched element ( start index and end index ) to add css class based on if the letter is between these indexes .

I made an example that might help you out using your code .

about 4 years ago · Santiago Trujillo Relatório

0

Thanks to @epascarello comment, I have updated the function as below:

const Highlighter = ({
  children,
  highlight,
}: {
  children: any;
  highlight: any;
}) => {
  if (!highlight) return children;
  const regexp = new RegExp(highlight, "i"); // HERE IS THE CHANGE
  const matches = children.toString().match(regexp);
  var parts = children
    .toString()
    .split(new RegExp(`${highlight.replace()}`, "i")); // HERE IS THE CHANGE

  for (var i = 0; i < parts.length; i++) {
    if (i !== parts.length - 1) {
      let match = matches[i];
      // While the next part is an empty string, merge the corresponding match with the current
      // match into a single <span/> to avoid consequent spans with nothing between them.
      while (parts[i + 1] === "") {
        match += matches[++i];
      }

      parts[i] = (
        <React.Fragment key={i}>
          {parts[i]}
          <span className="highlighted">{match}</span>
        </React.Fragment>
      );
    }
  }
  return <div className="highlighter">{parts}</div>;
};

So, instead of using the flag g which is for global search, I changed it to flag i which is used for insensitive case search. This achieves the result that I wanted which is to highlight the text regardless of uppercase/lowercase.

about 4 years ago · Santiago Trujillo 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