Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing %1 and %2 in my javascript string [duplicate]

Tags:

javascript

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.

like image 469
Bronzato Avatar asked May 04 '13 07:05

Bronzato


1 Answers

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

like image 59
elclanrs Avatar answered Oct 20 '22 01:10

elclanrs