Regex ignore patterns

43 Views Asked by At

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 &amp; and < with &lt; 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 &amp; and &lt; from being matched?

I tried (new RegExp(^(?!&amp;|&lt;)(${patterns.join('|')}), 'g') but it's not working

1

There are 1 best solutions below

0
Wiktor Stribiżew On

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:

let html = "&lt; &amp; & amp";
const patterns = ['&', 'amp'];
const rx = new RegExp(`&(amp|lt);|${patterns.join('|')}`, 'g');
console.log(
    html.replace(rx, (match, group) => group === undefined ? `<strong>${match}<strong>` : match)
 );

Since &(amp|lt);| is the first alternative, the (amp|lt) will be the first group and it is assigned to group in your arrow function declaration, so if you check if group equals undefined you can learn if the undesired pattern was matched, and if it did, just return the whole match (match), else, return the tagged match.