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 .