Let's say we have a string:
"The quick brown fox jumps over the lazy dog"
You search within that string for "ove ver".
The result should be that the word "over" is highlighted.
My code so far:
'The quick brown fox jumps over the lazy dog'
.replace(/ove|ver/g, s => s.replace(/\w/g, '<mark>$&</mark>'))
The result should be similar to this demo on regex101.
CodePudding user response:
You can use that lookahead assertion but match a full word and highlight it:
const s = 'The quick brown fox jumps over the lazy dog';
var r = s.replace(/(?=ove|ver)\w /g, '<mark>$&</mark>');
console.log(r);
//=> The quick brown fox jumps <mark>over</mark> the lazy dog
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You could also search for a partial match using the alternation inside a non capture group (?:ove|ver)
surrounded by optional word characters \w*
const regex = /\w*(?:ove|ver)\w*/g;
const s = 'The quick brown fox jumps over the lazy dog';
console.log(s.replace(regex, "<mark>$&</mark>"));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>