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

Winapi c++: DialogBox hangs when breaking a loop -

vb.net - Font adding using PDFsharp -

javascript - jQuery iScroll clickable list elements while retaining scroll? -