JavaScript RegEx用字符串替换以#开头的单词

时间:2014-01-14 14:31:36

标签: javascript regex node.js

我使用下面的函数用字符串中的#替换单词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中看到的那样。 我做错了什么?

2 个答案:

答案 0 :(得分:3)

我猜replace会更合适:

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

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

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

答案 1 :(得分:1)

  • 您正在更改循环内的字符串。 re.exec使用lastIndex属性存储下一场比赛的开始位置。将“#workspace_name”替换为“127”时,messageString会变短。
  • 你开始消耗空间。

我认为应该这样做:

var messageString = "The folder #folder_name was removed from the workspace #workspace_name by #user_name"
var re = /(^|\W)#(\w+)/g, match;
var changedString = messageString;
while (match = re.exec(messageString)) {
    changedString = changedString.replace(match[0], match[1] + extra_data[match[2]]);
}