This is a part of bigger problem I'm trying to solve. I'll mention both of them.
Say, with a needle like bi
and haystack like Bird
, I could use the following code to search for the needle and apply some formatting to the haystack:
const regExp = new RegExp(/bi/, 'gi');
inputStr = inputStr.replace(regExp, '*' + '$&' + '@');
The above would mutate the inputStr like: *Bi@rd
(I'll explain later why I'm formatting.)
Now, is it possible to search this modified haystack *Bi@rd
for a needle ir
?
Bigger problem I'm trying to solve: Finding multiple needles in a haystack and highlighting them. Needles will come in the form of a space separated string. The haystack is user names, so not very long.
This is one of the solutions I came up with:
function highlighter(inputStr, searchQuery) {
const needles = searchQuery.split(' ');
let regExp;
needles.forEach((pattern) => {
regExp = new RegExp(pattern, 'gi');
inputStr = inputStr.replace(regExp, '*' + '$&' + '@');
});
const highlightedStr = inputStr.replace(/[*]/g, '<span class="h">').replace(/[@]/g, '</span>');
return highlightedStr;
}
My solution will fail if I try to highlight bi ir
in Bird
.
I've another solution but it's complicated. So wondering, short of using a library, what's the best way to solve my problem.