2

I want to replace all the occurrences of a string in javascript;

In my search text I have special chars and I cant escape them;

I need to replace the ${wid} text with the given string;

I have this function:

    function replaceAll(find, replace, str) {
        return str.replace(new RegExp(find, 'g'), replace);
    }

that should do the job;

var inner_code = replaceAll('/\$\{wid\}/', 'id_' + widget.model_attributes.id, widget.code);

widget.model_attributes.id is a positive integer number

widget.code is:

<div id="code_50"><div id="${wid}"></div>
<script type="text/javascript">
    $("#${wid}").text("hello world");
</script></div>

p.s: this is not a duplicate question; i don't know how to escape special chars using JS

Ionut Flavius Pogacian
  • 4,750
  • 14
  • 58
  • 100

2 Answers2

2

You need to escape the backslash itself. Try:

replaceAll('\\$\\{wid\\}', 'id_' + ...)

You are writing a JavaScript string literal. You want the string content to be "\$\{wid\}", because that is the RegExp source code you want. Since backslash means something in string literals, you need to escape it (by putting another backslash in front of it).

I would recommend not using the replaceAll function, and just writing:

var inner_code = widget.code.replace(/\$\{wid\}/g, 'id_' + widget.model_attributes.id);

That allows you to keep the RegExp as a RegExp literal, which is much easier to read than going through a string literal and the RegExp constructor.

lrn
  • 64,680
  • 7
  • 105
  • 121
1

You are not creating your regexp correctly. Use a literal expression:

function replaceAll(find, replace, str) {
    return str.replace(new RegExp(find), replace);
}
var inner_code = replaceAll(/\${wid}/g, 'id_' + widget.model_attributes.id, widget.code);
Blazes
  • 4,721
  • 2
  • 22
  • 29