我正在使用下面的函数用来自字符串的#替换单词beginig,并使用来自extra_data对象的名称完全相同的变量。

var messageString = "The folder #folder_name was removed from the workspace #workspace_name by #user_name"
var re = /(?:^|\W)#(\w+)(?!\w)/g, match;
while (match = re.exec(messageString)) {
  messageString = messageString.replace(match[0],extra_data[match[1]]);
  console.log("I am here--------------------------------------------->1");
  console.log(messageString);
}


控制台日志

I am here--------------------------------------------->1
The folder23545 was removed from the workspace #workspace_name by #user_name
I am here--------------------------------------------->1
The folder23545 was removed from the workspace127 by #user_name


上面的代码仅替换2个实例,有时还会占用空白空间,如在工作区127上所见。
我究竟做错了什么?

最佳答案

我想replace在这里会更合适:

result = messageString.replace(/#(\w+)/g, function(_, $1) { return extra_data[$1] })


或者,仅替换以#开头的单词:

.replace(/(^|\W)#(\w+)/g, function(_, $1, $2) { return $1 + extra_data[$2] })

08-04 03:32