Highlighting search terms in page content
Honestly, there are probably cleaner ways to do this without touching the DOM structure 1 , but this little approach has worked fine for me so far.
Here’s a quick demo:
To be, or not to be: that is the question. Whether 'tis nobler in the mind to suffer the slings and arrows of outrageous fortune, or to take arms against a sea of troubles and by opposing end them. To die, to sleep; no more; and by a sleep to say we end the heartache and the thousand natural shocks that flesh is heir to, 'tis a consummation devoutly to be wished. To die, to sleep; to sleep, perchance to dream—ay, there's the rub: for in that sleep of death what dreams may come when we have shuffled off this mortal coil, must give us pause. There's the respect that makes calamity of so long life; for who would bear the whips and scorns of time, the oppressor's wrong, the proud man's contumely, the pangs of despised love, the law's delay, the insolence of office, and the spurns that patient merit of th'unworthy takes, when he himself might his quietus make with a bare bodkin? who would fardels bear, to grunt and sweat under a weary life, but that the dread of something after death, c++ the undiscovered country from whose bourn no traveler returns, puzzles the will and makes us rather bear those ills we have than fly to others that we know not of?
And the code behind the highlighting:
const const highlightSearchTerm: (searchTerm: string, content: string) => string | (string | JSX.Element)[]highlightSearchTerm = (searchTerm: stringsearchTerm: string, content: stringcontent: string) => {
if (!searchTerm: stringsearchTerm || !content: stringcontent) return content: stringcontent;
try {
const const escapedTerm: stringescapedTerm = searchTerm: stringsearchTerm.String.replace(searchValue: {
[Symbol.replace](string: string, replaceValue: string): string;
}, replaceValue: string): string (+3 overloads)
Passes a string and
{@linkcode
replaceValue
}
to the `[Symbol.replace]` method on
{@linkcode
searchValue
}
. This method is expected to implement its own replacement algorithm.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const const regex: RegExpregex = new var RegExp: RegExpConstructor
new (pattern: RegExp | string, flags?: string) => RegExp (+2 overloads)
RegExp(`(${const escapedTerm: stringescapedTerm})`, "gi");
const const parts: string[]parts = content: stringcontent.String.split(splitter: {
[Symbol.split](string: string, limit?: number): string[];
}, limit?: number): string[] (+1 overload)
Split a string into substrings using the specified separator and return them as an array.split(const regex: RegExpregex);
return const parts: string[]parts.Array<string>.map<string | JSX.Element>(callbackfn: (value: string, index: number, array: string[]) => string | JSX.Element, thisArg?: any): (string | JSX.Element)[]Calls a defined callback function on each element of an array, and returns an array that contains the results.map((part: stringpart, i: numberi) =>
part: stringpart.String.toLowerCase(): stringConverts all the alphabetic characters in a string to lowercase.toLowerCase() === searchTerm: stringsearchTerm.String.toLowerCase(): stringConverts all the alphabetic characters in a string to lowercase.toLowerCase() ? (
<JSX.IntrinsicElements.mark: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>mark Attributes.key?: Key | null | undefinedkey={i: numberi}>{part: stringpart}</JSX.IntrinsicElements.mark: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>mark>
) : (
part: stringpart
)
);
} catch (function (local var) error: unknownerror) {
return content: stringcontent;
}
};
The function takes in two parameters, the search term and the text you are scanning through. If either of them doesn’t exist, it just returns the original content.
Next, it escapes special regex characters. This step is easy to overlook but really important because search terms might include stuff like ., +, or ?, which have special meanings in regex.
For example, try searchin c++ in the example below:
In the first example (escaped), the highlight works perfectly. In the second, it doesn’t because the + was treated as a regex operator, not a literal character.
Here is the line that handles this:
const escapedTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
That expression basically adds a backslash in front of all regex-special characters so they’re treated as normal text.
After that, we build a regex and wrap our term in parentheses:
const regex = new RegExp(`(${escapedTerm})`, "gi");
The parentheses matter because they keep the matched term in the split result. Without them, it wouldn’t show up at all.
Then we split the content around those matches:
const parts = content.split(regex);
Finally we map through all the parts and if the text matches our search term, we wrap it in a <mark> element:
<mark key={i}>{part}</mark>
We can then style the marked words using CSS like so:
mark {
background-color: #fffb0d;
}
And that’s pretty much it.
Wrapping the logic in a try...catch just makes sure any weird input doesn’t break the whole thing.
Footnotes
-
Using the CSS Custom Highlight API ↩