문제

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)
도움이 되었습니까?

해결책

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

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top