Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
I'm new to backreference. I have an array and need to replace it in string.
Here's my try:
var cc = ["book","table"]; var str = "The $1 is on the $2"; var newstr = str.replace(cc, "$2, $1"); console.log(newstr)
replace
That's... hmm, I'm not sure I can understand the kind of confusion of ideas that would lead you to write such a thing...
Try this:
newstr = str.replace(/\$(\d)+/g,function(_,id) {return cc[id-1];});
Add a comment
var cc = ["book","table"]; var str = "The $1 is on the $2"; var newstr = str.replace('$1', cc[0]).replace('$2', cc[1]); alert(newstr);
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
replaceexpects a regex; the replacement tokens map to different capturing groups.