I'm trying to highlight some text but I want to exclude some patterns from being matched.
First I'm securing the text, replacing & with & and < with < then I look for matches and add the strong tag around it
html.replace(new RegExp(`${patterns.join('|')}`, 'g'), (match, group) => {
return `<strong>${match}<strong>`;
});
So if I have a text like amp & and try to highlight amp it becomes <strong>amp<strong> &<strong>amp<strong>;. How can I ignore & and < from being matched?
I tried (new RegExp(^(?!&|<)(${patterns.join('|')}), 'g') but it's not working
You can match and capture - all or part of - the strings you want to skip, and then check if that group matched in the arrow function used as a replacement:
Since
&(amp|lt);|is the first alternative, the(amp|lt)will be the first group and it is assigned togroupin your arrow function declaration, so if you check ifgroupequalsundefinedyou can learn if the undesired pattern was matched, and if it did, just return the whole match (match), else, return the taggedmatch.