Replacing %1 and %2 in my javascript string -


lets have following string in javascript code:

var mytext = 'hello %1. how %2?'; 

now inject in place of %1 , %2 in above string. can do:

var result = mytext.replace('%1', 'john').replace('%2', 'today'); 

i wonder if there better way of doing calling 2 times replace function.

thanks.

how little format helper? that's need:

function format(str, arr) {   return str.replace(/%(\d+)/g, function(_,m) {     return arr[--m];   }); }  var mytext = 'hello %1. how %2?'; var values = ['john','today'];  var result = format(mytext, values);  console.log(result); //=> "hello john. how today?" 

demo: http://jsbin.com/uzowuw/1/edit


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -