0

I have problem with regexp for replace html code in string. I had tried online regexp tester with match, but something causes that I canť replace. ${ProductEAN} is what I want replace. Any idea what is wrong?

The string is here:

<label for="ProductEAN" id="ProductEAN" class="col-sm-3 control-label">${ProductEAN}</label>

Javascript code:

let strToReplace = 'ProductEAN';
let reg = new RegExp('/(\$\{'+strToReplace+'\})/','g')
        str.replace(reg,'some text');
  • Make sure to mark the best answer as accepted if it helped you. That way it doesn't show up as unanswered. – rvighne Jul 15 '16 at 20:29

4 Answers4

2

The RegExp constructor doesn't need slashes (/.../) around the expression, that is only for regex literals. And when you backslash-escape characters, they are escaped in the string passed to the constructor, but pass unescaped to the actual regex expression. They need to be double-escaped. So, change the line to this:

let reg = new RegExp('\\$\\{'+strToReplace+'\\}','g');
rvighne
  • 20,755
  • 11
  • 51
  • 73
0

You need proper escaping the backslashes

reg = new RegExp('\\$\\{' + strToReplace + '\\}', 'g');

and an assignment for the replaced string.

newString = str.replace(reg,'some text');

var element = document.getElementById('ProductEAN'),
    strToReplace = 'ProductEAN',
    reg = new RegExp('\\$\\{' + strToReplace + '\\}', 'g');

element.innerHTML = element.innerHTML.replace(reg,'some text');
<label for="ProductEAN" id="ProductEAN" class="col-sm-3 control-label">${ProductEAN}</label>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

This should do it:

var str = '<label for="ProductEAN" id="ProductEAN" class="col-sm-3 control-label">${ProductEAN}</label>';
var strToReplace = 'ProductEAN';
var reg = new RegExp('(\\${'+strToReplace+'})','g')
str.replace(reg,'some text');
tpdietz
  • 1,358
  • 9
  • 17
-1

Try this:

new RegExp('\$\{' + strToReplace + '\}','g')

When invoked with RegExp, you don't have to put the /'s in. You also shouldn't need the ()'s.

More info here: http://www.javascriptkit.com/jsref/regexp.shtml

Also, you can get rid of the let's. They aren't needed.

raphael75
  • 2,982
  • 4
  • 29
  • 44