Home > Back-end >  What is the RegExp that replace all the "." occurrences inside "<code>" ta
What is the RegExp that replace all the "." occurrences inside "<code>" ta

Time:10-04

I would like to replace all the dots inside the HTML tag <code> with the word " dot ".

If I do like this it will change only the first occurrence. I would like to change them all.

const str = 'Some text <code >this.is.a.class</code> and <code>this.another.thing</code>';

const res = str.replaceAll(/(<code[^>]*>.*?)(\.)(.*?<\/code>)/g, "$1 dot $3");

console.log(res);

// Some text <code >this dot is.a.class</code> and <code>this dot another.thing</code>

Why it is changing only the first?

CodePudding user response:

You can use a String#replace method with a callback function:

const str = 'Some text <code >this.is.a.class</code> and <code>this.another.thing</code>';
const res = str.replaceAll(/(<code[^>]*>)([\s\S]*?<\/code>)/g, (_,x,y) => `${x}${y.replaceAll(".", " dot ")}`);
console.log(res);

The (<code[^>]*>)([\s\S]*?<\/code>) regex matches and captures the open code tag into Group 1 (x variable), and then captures any zero or more chars as few as possible and then the close code tag into Group 2 (y variable). When replacing, all dots in y (Group 2 captured value) are replaced with DOT inside the arrow function.

Note that [\s\S] matches any chars including line break chars, . does not match line break chars (at least by default).

  • Related