简体   繁体   English

AngularsJS JavaScript匹配单词并添加字符串

[英]AngularsJS JavaScript Matching Words and Adding String

I have a long text in contentString . 我在contentString有一个长文本。

In $scope.listKeyWords , I have some keywords (car, house, red, cool) $scope.listKeyWords ,我有一些关键字(car,house,red,cool)

I need to match this keywords in my text and add some stuff like: 我需要在文本中匹配此关键字,并添加一些内容,例如:

Input contentString : 输入 contentString

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

Output expected: 预期输出:

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

[EDITED] [SOLUTION] thanks to @Barth Zalewski [编辑] [解决]感谢@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>");
}

How can I proceed? 我该如何进行?

Thanks for your help 谢谢你的帮助

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

The \\b denotes a "word boundary" so that only whole words will be replaced. \\b表示“单词边界”,因此仅替换整个单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM