简体   繁体   English

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

[英]javascript style all words between special characters

I am looking to style some words in a string that contain special characters. 我正在寻找包含特殊字符的字符串中某些单词的样式。 For instance If I have 例如,如果我有

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

I would like it to look like this without the special characters 我希望它看起来像没有特殊字符

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

How can I replace the end of the single quote with in the method below? 如何在下面的方法中替换单引号的结尾?

This is what I have so far. 到目前为止,这就是我所拥有的。

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;
}

The other idea I have was to iterate through the string with .split() and check if the word ends with a single quote then replace that but I don't like that solution. 我的另一个想法是使用.split()遍历字符串,并检查单词是否以单引号结尾,然后替换该单词,但我不喜欢该解决方案。

You may perform a single replace operation to achieve what you need: 您可以执行一次replace操作来实现所需的功能:

 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); 

The pattern - '([^']+)'|\\[([^\\][]+)] - matches '...' and [...] substrings and captures their contents, and replaced with the span tags using those contents as the attribute and node value. 模式- '([^']+)'|\\[([^\\][]+)] -匹配'...'[...]子字符串并捕获其内容,并替换为span标记使用这些内容作为属性和节点值。

Pattern details 图案细节

  • '([^']+)' - a single quote, then Group 1 (later referred to with $1 ) capturing 1+ chars other than ' , and then a ' '([^']+)' -单引号,然后是第1组(后来称为$1 ),捕获了除' 1+个字符,然后是'
  • | - or - 要么
  • \\[([^\\][]+)] - a [ char, then Group 2 (later referred to with $2 ) capturing 1+ chars other than [ and ] , and then a ] . \\[([^\\][]+)] -a [ char,然后是第2组(后称$2 ),捕获了除[]以外的1+个char,然后是a ]

Since $n backreferences are always initialized with an empty string, there is no problem using $1$2 in the replacement: only one of them contains text during each replacement, the other is empty. 由于$n反向引用始终使用空字符串初始化,因此在替换中使用$1$2没问题:每次替换期间,只有一个包含文本,另一个为空。

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

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