2

I am trying to replace values in a string template, and I am trying to do so like this:

for (var i in replacements) {
    var regexp = new RegExp('\$\{' + i + '\}', 'g');
    template = template.replace(regexp, replacements[i]);
}

Here is the template that I am trying to replace values in:

<?php
class ${className} {

}

When I do a console.log(i, replacements[i]), I get className Test, but it doesn't replace it in the final template. It doesn't modify it at all. Am I doing this wrong?

The output I am looking for is this:

<?php
class Test {

}
Get Off My Lawn
  • 27,770
  • 29
  • 134
  • 260

1 Answers1

2

Double-escape the special characters, once for the string and once for the Regex.

Also, no need to escape the curly brackets.

var replacements = {
  className: 'Test'
}

var template = '<?php class ${className} { }';

for (var i in replacements) {
  var regexp = new RegExp('\\${' + i + '}', 'g');
  template = template.replace(regexp, replacements[i]);
}

console.log(template);
TimoStaudinger
  • 34,772
  • 13
  • 76
  • 86