Replacing Text Inside of Curley Braces JavaScript

Oliver Spryn picture Oliver Spryn · Mar 17, 2011 · Viewed 18.7k times · Source

I am trying to use JavaScript to dynamically replace content inside of curly braces. Here is an example of my code:

var myString = "This is {name}'s {adjective} {type} in JavaScript! Yes, a {type}!";
var replaceArray = ['name', 'adjective', 'type'];
var replaceWith = ['John', 'simple', 'string'];

for(var i = 0; i <= replaceArray.length - 1; i ++) {
  myString.replace(/\{replaceArray[i]\}/gi, replaceWith[i]);
}

alert(myString);

The above code, should, output "This is John's simple string in JavaScript! Yes, a string!".

Here is what happens:

  1. we are given a string with values in braces that need replaced
  2. a loop uses "replaceArray" to find all of the values in curly braces that will need replaced
  3. these values, along with the curly braces, will be replaced with the corresponding values in the "replaceWith" array

However, I am not having any luck, especially since one value may be replaced in multiple locations, and that I am dealing a dynamic value inside of the regular expression.

Can anyone help me fix this, using a similar setup as above?

Answer

Yi Jiang picture Yi Jiang · Mar 17, 2011

First, String.replace is not destructive - it doesn't change the string itself, so you'll have to set myString = myString.replace(...). Second, you can create RegExp objects dynamically with new RegExp, so the result of all that would be:

var myString = "This is {name}'s {adjective} {type} in JavaScript! Yes, a {type}!",
    replaceArray = ['name', 'adjective', 'type'],
    replaceWith = ['John', 'simple', 'string'];

for(var i = 0; i < replaceArray.length; i++) {
    myString = myString.replace(new RegExp('{' + replaceArray[i] + '}', 'gi'), replaceWith[i]);
}