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 {

}
2
  • 1
    '\\$\\{' + i + '\\}', 'g' Commented Jul 19, 2016 at 18:55
  • You could use this answer stackoverflow.com/a/500144/1262960 Commented Jul 19, 2016 at 19:00

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.