Javascript / jQuery String Manipulation,将<b>标记在所有文本的字符串周围,后面直接用冒号

时间:2016-07-29 02:06:02

标签: javascript jquery regex

我有一个看起来像这样的字符串:

var string = 'Item 1: Description of Item 1 | Item 2: Description of Item 2 | Item 3: description of item 3';

我想操纵字符串以在标题周围包裹b标签并删除|符号。所以它变成了:

var fixedString = <b>Item 1:</b> Description of Item 1 <b>Item 2:</b> Description of item 2 <b>Item 3:</b> Description of Item 3

我尝试了一些正则表达式,但我认为我没有做到这一点。

2 个答案:

答案 0 :(得分:1)

您的模式需要匹配:

  1. 字符串的开头 a |
  2. 任何领先的空间
  3. 非冒号字符
  4. 冒号
  5. #3&amp ;; #4应放在<b></b>之间。

    正则表达式翻译将使用

    (?:^|\|)\s*([^:]*:)
    

    然后将其用作替换字符串:

    <b>$1</b>
    

    此处,$1指的是第一个捕获组内的字符。

    var string = 'Item 1: Description of Item 1 | Item 2: Description of Item 2 | Item 3: description of item 3';
    var fixedOutput = string.replace(/(?:^|\|)\s*([^:]*:)/g, '<b>$1</b>');
    document.body.innerHTML = fixedOutput;

    Regex101 Demo

答案 1 :(得分:1)

尝试以下正则表达式。

var string = 'Item 1: Description of Item 1 | Item 2: Description of Item 2 | Item 3: description of item 3';

var fixedString = string.replace(/([^:]+)([^|]+\|?)/g,"<b>$1</b>$2");
console.log(fixedString);

使用带有匹配的否定字符类。

{{1}}

Online demo