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

c++ - Function signature as a function template parameter -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -

How to call a javascript function after the page loads with a chrome extension? -