javascript样式特殊字符之间的所有单词

时间:2017-12-05 19:35:01

标签: javascript regex

我希望在包含特殊字符的字符串中设置一些单词的样式。 例如,如果我有

"I want to style words in single quotes 'blue' and brackets [red]. There are multiple 'blue' and [red] words in a string"

我希望它看起来没有特殊字符

"I want to style words in single quotes <span class='blue'>blue</span> and brackets <span class='red'>red</span>..."

如何在下面的方法中替换单引号的结尾?

这是我到目前为止所做的。

highlightMessage(message) {
    var text = message.replace(/[\[']+/g, "<span class='red'>")
    var text = message.replace(/]\]']+/g, "</span")
    var text = message.replace(/'/g, "<span class='blue'>")
    //how can I replace the end of the single quote with </span>
    //the method above replaces it with <span class='blue'>

    return message;
}

我的另一个想法是使用.split()遍历字符串并检查单词是否以单引号结尾然后替换它,但我不喜欢该解决方案。

1 个答案:

答案 0 :(得分:2)

您可以执行单个replace操作来实现您的需求:

&#13;
&#13;
var s = "I want to style words in single quotes 'blue' and brackets [red]. There are multiple 'blue' and [red] words in a string";
var res = s.replace(/'([^']+)'|\[([^\][]+)]/g, "<span class='$1$2'>$1$2</span>")
console.log(res);
&#13;
&#13;
&#13;

模式 - '([^']+)'|\[([^\][]+)] - 匹配'...'[...]子字符串并捕获其内容,并使用这些内容作为属性和节点值替换为span标记。

模式详情

  • '([^']+)' - 一个引号,然后是第1组(后来引用$1)捕获除'以外的1个字符,然后是'
  • | - 或
  • \[([^\][]+)] - [个字符,然后是第2组(后来称为$2),捕获除[]以外的1个字符,以及然后是]

由于$n反向引用始终使用空字符串初始化,因此在替换中使用$1$2没有问题:每次替换时只有一个包含文本,另一个是空的。

相关问题