-2

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)
Tropicalista
  • 3,097
  • 12
  • 44
  • 72
  • I think you're confusing things here... `replace` expects a regex; the replacement tokens map to different capturing groups. – elclanrs Dec 13 '13 at 04:49
  • Convert array into string. http://www.w3schools.com/jsref/jsref_tostring_array.asp – Ishan Jain Dec 13 '13 at 04:51
  • Check my answer here, that should help you out http://stackoverflow.com/questions/16371871/replacing-1-and-2-in-my-javascript-string/16371896#16371896 – elclanrs Dec 13 '13 at 04:52

2 Answers2

1

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];});
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Try this:

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);
Ringo
  • 3,795
  • 3
  • 22
  • 37