0

I have an string, but at certain points in the string it has dynamic values. I want to find those points in the string and replace them with values from an array.

Let's say I have:

var array = ['string', 'value'];
var string = 'This is a {1}, and this is a {2}.';

Now I need to figure out a way to replace {1}, with the value of the first index in the array and replace {2} with the value of the second index of the array.

So the string would like this:

This is a string, and this is a value.

This seems so simple, but I am breaking my head on this. I can't find a way to do this easily.

3 Answers 3

5

You can use replace with a regular expression and a function:

string.replace(/{(\d+)}/g, function(match, n) {
  return array[n-1];
});

You can also check n < 1 || n > array.length to provide a fallback value in case the number is out of bounds.

Alternatively, the new ES6 way is using tagged template strings

function tag(strings, ...values) {
  var parts = [];
  for(var i=0; i<strings.length; ++i)
    parts.push(strings[i], array[values[i]-1]);
  return parts.join('');
}
tag`This is a ${1}, and this is a ${2}.`
Sign up to request clarification or add additional context in comments.

3 Comments

When I use your first example, the '{' and '}' are still in the string, though the 1 and 2 are replaced properly.
The match variable contains either '{1}' or '{2}', but only the value itself is replaced and not the brackets.
Okay, thank you. Now it works. Apparently, somewhere in my code that made the string, it added two {{ and two }}, instead of one. Now it works perfectly.
1

like this

string.replace(/\{(\d+)\}/g, function(m, n){
  return array[n-1]
})

1 Comment

When I use your first example, the '{' and '}' are still in the string, though the 1 and 2 are replaced properly.
1

You can use Array.prototype.reduce:

var StringHelper = {
  format: function(format, args) {
    return args.reduce(function(result, currentReplace, currentReplaceIndex) {
      result = result.replace("{" + (currentReplaceIndex + 1) + "}", args[currentReplaceIndex]);

      return result;
    }, format);
  }
};

var sourceString = "My name is {1} and I'm {2} years old";
var replaceItems = ["Matías", "31"];

var parsedString = StringHelper.format(sourceString, replaceItems);

alert(parsedString);

It's a good alternative to regular expressions, and I'm not absolutely sure if I did a jsPerf test in the right way, but it shows that this approach outperforms the regular expression one.

4 Comments

This also worked for me, though I prefer the accepted answer.
@DijkeMark I believe you don't know the power of encapsulation. Check my updated answer which generalizes the solution into an object function.
@DijkeMark If you can't use ES6 or above, that simple string formatting function is the closest solution to your issue and as I said, it seems like it outperforms regular expressions. BTW I'll leave my answer for further readers.
I see, thank you for this explanation. I will keep it in mind for further cases.

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.