AngularJS JavaScript匹配单词和添加字符串

时间:2014-12-03 15:27:32

标签: javascript angularjs angularjs-scope

我在contentString中有一段很长的文字。

$scope.listKeyWords中,我有一些关键字(汽车,房子,红色,酷)

我需要在文字中匹配这些关键字并添加一些内容,例如:

输入 contentString

Hello there, I have a very nice car. It is very cool.

预期输出

Hello there, I have a very nice <u>car</u>. It is very <u>cool</u>.

[EDITED] [解决方案]感谢@Barth Zalewski

for (var k = 0, word; word = $scope.listKeyWords[k]; k++) {
   var re = new RegExp(word, 'g');
   contentString = contentString.replace(re, "<u>" + word + "</u>");
}

我该怎么办?

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

for (var k = 0, word; word = $scope.listKeyWords[k]; k++) {
  contentString = contentString.replace(new RegExp("/\\b" + word + "\\b/"), "<u>" + word + "</u>");
}

\b表示&#34;字边界&#34;这样只会替换整个单词。

相关问题