Replacing %1 and %2 in my javascript string -
this question has answer here:
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?"
Comments
Post a Comment