Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

336
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda