Error undefined using replace ()

7

I'm trying to make a kind of people marking, I tried, but I did not succeed. Where is the error ??

var nome =["Ana", "João", "Maria", "José"];
var frase = "@[1] é casado com @[0], e @[2] é casada com @[3].";

var msg = frase.replace(/@\[(\d)\]/gmi, nome["$1"]);

document.write(msg);

The code should return:

  

John is married to Anna, and Mary is married to Joseph.

    
asked by anonymous 13.11.2015 / 00:01

1 answer

9

Well, writing nome["$1"] , you're passing string to index of your array , and since position does not exist, undefined is returned to you by default. This means that the value is undefined.

So, all the rest of your code is correct, but to fulfill your goal of changing the index according to the one in the sentence, just use an anonymous function like this:

msg = frase.replace(/@\[(\d)\]/gmi, function(matchedText, $1, offset, str){return nome[$1]})

Your complete code (working) would look like this:

var nome =["Ana", "João", "Maria", "José"];
var frase = "@[1] é casado com @[0], e @[2] é casada com @[3].";

msg = frase.replace(/@\[(\d)\]/gmi, function(matchedText, $1, offset, str){return nome[$1]})

document.write(msg);

See a similar question: link

More on the subject here .

    
13.11.2015 / 00:36