string替换数组映射

时间:2016-11-14 15:18:25

标签: javascript arrays

我在列表中有数百名用户,下面只是一个示例列表:



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);




测试字符串返回仍然相同,不会替换为电子邮件。我做的代码是否优化了?

1 个答案:

答案 0 :(得分:0)

您需要使用返回值更新变量。

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);