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?
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.
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.