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