我有一个看起来像这样的字符串:
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
我尝试了一些正则表达式,但我认为我没有做到这一点。
答案 0 :(得分:1)
您的模式需要匹配:
|
#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;
答案 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}}