Lets say I have the following string in my javascript code:
var myText = 'Hello %1. How are you %2?';
Now I would like to inject something in place of %1 and %2 in the above string. I can do:
var result = myText.replace('%1', 'John').replace('%2', 'today');
I wonder if there is a better way of doing than calling 2 times the replace function.
Thanks.
How about a little format
helper? That's basically what you need:
function format(str, arr) {
return str.replace(/%(\d+)/g, function(_,m) {
return arr[--m];
});
}
var myText = 'Hello %1. How are you %2?';
var values = ['John','today'];
var result = format(myText, values);
console.log(result); //=> "Hello John. How are you today?"
Demo: http://jsbin.com/uzowuw/1/edit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With