Well, when writing nome["$1"]
, you’re passing a string
as index
of your array
, and as the 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 informed in the sentence, just use an anonymous function as follows:
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:
https://stackoverflow.com/a/8990209/4720858
More on the subject here.
What the code is returning?
– Marco Aurélio Deleu
@Marcoauroleidium "Undefined is married to Undefined, and Undefined is married to Undefined"... ;)
– Daniel
Tries
var msg = frase.replace(/@\[(\d)\]/gmi, nome[0]);
just to confirm that the error is at ["$1"]– Marco Aurélio Deleu