How to wrap content,which is wrapped inside a squarebrackets, using span tag in a string gloabally for all the occurences?

Viewed 44

I have the rquirement of highlighting the text conent,which is wrapped between sqaure brackets, in a string. The content have more than one occurences. For that I need to wrap that in a span tag with some class to highlight it gloabally for all the conents which are wrapped inside the square brackets[].

My string looks like as follows

let str = "<p>[If you no] longer wish to receive emails [from this sender] , pleas?ick here and confirm your [request] .</p>";

The expected result is

let str = "<p><span class="highlight">[If you no]</span> longer wish to receive emails <span class="highlight">[from this sender]</span> , pleas?ick here and confirm your <span class="highlight">[request]</span> .</p>";

Currentlt the way I am doing is as follows

let str = "<p>[If you no] longer wish to receive emails [from this sender] , pleas?ick here and confirm your [request] .</p>"
let matched = str.match(/\[(.*?)\]/g);
let someString=matched.map(element=> 
       str.replace(element,`<span class="highlight">${element}</span>`)
      )
      console.log(someString);

If this approach is wrong then please give some best ways to solve this issue. Thanks in advance.

1 Answers

The $1 in the replacement will be used to inject the element captured in te first group in the pattern..

In another scenario if you have another capturing group the replacement would be $2 instead

MDN - RegExp.$1-$9

let str = "<p>[If you no] longer wish to receive emails [from this sender] , pleas?ick here and confirm your [request] .</p>"
let pattern = /\[(.*?)\]/g
str = str.replace(pattern,'<span class="highlight">[$1]</span>')
console.log(str)
document.getElementById('result').innerHTML = str
.highlight {
background: yellow;
}
<div id="result"></div>

Related