我使用下面的函数将字符串中的单词 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 个实例,有时会占用空白空间,正如您在workspace127 中看到的那样。 我做错了什么?
最佳答案
我想replace
在这里更合适:
result = messageString.replace(/#(\w+)/g, function(_, $1) { return extra_data[$1] })
或者,仅替换以 #
开头的单词:
.replace(/(^|\W)#(\w+)/g, function(_, $1, $2) { return $1 + extra_data[$2] })
关于JavaScript RegEx 用于替换字符串中以 # 开头的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21116103/