I have encountered a peculiar issue with regex. I am attempting to validate user input in a contentEditable div using regex after each keydown event. The goal is to modify the text by highlighting specific words such as "hello" or "status" with
<span style="color: purple">hello<span>
. This works well with unique words, phrases, or pasted content. However, when I define both "hello" and "hello world" as keywords and type them in the contentEditable div, the regex only matches "hello," even though "hello world" is listed first in my array of strings.
Below is the code for my function:
searchByRegEx(wordsArr: string[], sentence: string): string {
let matchingWords = []; // array to store matching words
wordsArr.forEach((label) => {
const regEx = new RegExp(label, 'gi');
regEx.lastIndex = 0
let match = regEx.exec(sentence);
while (match) {
matchingWords.push(match[0]);
match = regEx.exec(sentence);
}
});
matchingWords = matchingWords.sort(function (a, b) {
return b.length - a.length;
});
matchingWords.forEach((word) => {
sentence = sentence.replaceAll(
word,
`<span style='color:${InputColorsHighlightValue.PURPLE}'>${word}</span>`
);
});
return sentence
}
}
Here is how I implement it:
if (this.labels) {
textToShow = this.searchByRegEx(['hello', 'hello world'], textToShow)
}
When testing in devTools, the regex correctly matches on paste, but not when typing manually. The input for the regex remains consistent:
https://i.sstatic.net/4uJ8u.png
If you encounter any issues or have advice, please feel free to provide assistance.