Undefined error using replace()

Asked

Viewed 216 times

7

I’m trying to make a sort of a people appointment, I made an attempt, but I was unsuccessful.
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 Anne, and Mary is married to Joseph.

  • What the code is returning?

  • @Marcoauroleidium "Undefined is married to Undefined, and Undefined is married to Undefined"... ;)

  • Tries var msg = frase.replace(/@\[(\d)\]/gmi, nome[0]); just to confirm that the error is at ["$1"]

1 answer

10


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.