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

342
Visualizações
¿Cómo resaltar el texto sin importar si está en mayúsculas o minúsculas, siempre que coincidan en 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;

El código anterior puede resaltar el texto como se usa a continuación:

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

y esto dará como resultado que el text se resalte. Sin embargo, si cambio el atributo de resaltado a: highlight="Text" , ya no resaltará el text porque hay una T mayúscula. ¿Cómo modifico este código para que coincida con las letras minúsculas/mayúsculas?

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

0

Deberá transformar el texto y el resaltado a minúsculas, después de hacer coincidir la palabra, use el índice del elemento coincidente (índice inicial e índice final) para agregar la clase css en función de si la letra está entre estos índices.

Hice un ejemplo que podría ayudarlo a usar su código.

about 4 years ago · Santiago Trujillo Relatório

0

Gracias al comentario de @epascarello, actualicé la función de la siguiente manera:

 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>; };

Entonces, en lugar de usar la bandera g que es para la búsqueda global, la cambié a la bandera i que se usa para la búsqueda insensible de mayúsculas y minúsculas. Esto logra el resultado que quería, que es resaltar el texto independientemente de mayúsculas/minúsculas.

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