简体   繁体   中英

How to replace multiple same word in string with different words

I want to replace multiple same word in string with different words.

For example,

"What is your %s name and %s name"

I want to replace first '%s' with 'first' and second '%s' with 'last' .

I think this might be cleaner:

['first', 'last'].forEach(function(tag) { x = x.replace('%s', tag); })

where x is the string you want to substitute into.

If you use a string as the first arg to replace it only does 1 replace.

var s = "What is ... ";
var r = s.replace("%s", "first")
         .replace("%s", "last");

More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

You could use String#replace and use Array#shift as callback for replacing %s .

This solution uses shift , because it serves a value from the array for each call, if an item for replacement is found. Usually a string or a function is needed as second parameter for replace . This proposal uses shift with a binded array for replacement.

Function#bind returns a function with the binded object.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

 var s = "What is your %s name and %s name?", t = s.replace(/%s/g, [].shift.bind(['first', 'last'])); console.log(t); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM