【问题标题】:Javascript and Regex - Strict match of words in the string [duplicate]Javascript和Regex - 字符串中单词的严格匹配[重复]
【发布时间】:2017-05-09 10:36:21
【问题描述】:

我有一个这样的字符串:

Free-coffee and coffee-free is free coffee

我只需要匹配和替换单个单词 free 而不是单词 {Free}-coffeecoffee-{free}

想法是在字符串中标记坏词并添加HTML标签<strong>,如下所示:

Free-coffee and coffee-free is <strong>free<strong> coffee.

我尝试使用空格,但如果这句话之前有空格,有时会失败。

这是我当前的正则表达式:

/(\sfree\s|\sfree|free\s)/ig

注意:这需要不区分大小写。

下面是代码示例:

var text = "Free-coffee and coffee-free is free coffee";
text = text.replace(/(\sfree\s|\sfree|free\s)/ig, " <strong>strong</strong> ");

请帮帮我。

【问题讨论】:

  • 使用text = text.replace(/(^|\s)(free)(?!\S)/ig, '$1&lt;strong&gt;$2&lt;/strong&gt;')

标签: javascript regex matching string-matching


【解决方案1】:

使用以下正则表达式模式:

var text = "Free-coffee and coffee-free is free coffee";
text = text.replace(/(^|\s)(free)(\s|$)/ig, "$1<strong>$2</strong>$3");

console.log(text);

(^|\s) - 确保 free 单词位于字符串的开头或前面有空格

(\s|$) - 确保 free 单词位于字符串末尾或后跟空格

【讨论】:

  • 谢谢!这项工作很棒!我扩展了这个 ot 匹配也其他字符并且工作完美!
  • 这是我的扩展代码(^|\s+|\“|\”|\‘|\’|\'|\"|\;|\:|\,)(free)(\'|\“|\”|\‘|\’|\"|\;|\:|\?|\!|\.|\,|\s+|$)
  • @IvijanStefanStipić,很高兴为您提供帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 2022-11-19
  • 2012-10-18
  • 2015-06-22
  • 1970-01-01
相关资源
最近更新 更多