0

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'.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

For a beginner like the OP I respectfully disagree.
Was the OP looking for an answer or an education?
how could this be simpler?
Well ['first','last'].forEach( tag => x = x.replace('%s', tag) ); would be "simpler", but one must walk before they run...
0

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

Comments

0

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);

5 Comments

It wasn't me, but your answer could use some explanation of HOW this works. For starters how func.bind() works... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@JohnHascall, maybe this is now better explained.
Better. Might also mention that [].shift() is really Array.prototype.shift() because [] is an Array literal.
i wrote it in the first line, with a link.
BTW, there is a similar 'fat arrow' approach: t = s.replace(/%s/g, () => ['first', 'last'].shift() );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.