Alvin Alvin - 20 days ago 7
Javascript Question

string replace array map

I have a hundreds of user in the list, below is just an example list :



var userList = [
{
"FullName": "test1",
"UserName": "test1",
"Email": "test1@test.com"
},
{
"FullName": "test2",
"UserName": "test2",
"Email": "test2@test.com"
}
];

var userStr = "test1 is doing a test2";
userList.map((user) => {
userStr.replace(RegExp(user.FullName,"gi"), user.Email)
})

console.log(userStr);





The test string return is still the same and is not replace with email. Is the code I do optimize?

Answer

You need to update the variable with the returned value.

var userList = [{
  "FullName": "test1",
  "UserName": "test1",
  "Email": "test1@test.com"
}, {
  "FullName": "test2",
  "UserName": "test2",
  "Email": "test2@test.com"
}];

var userStr = "test1 is doing a  test2";
userList.forEach((user) => userStr = userStr.replace(RegExp(user.FullName, "gi"), user.Email))

console.log(userStr);

Comments