在特定字符串的开头和结尾处替换字符

时间:2018-12-03 14:38:45

标签: javascript regex

假设此字符串:

b*any string here*

如果存在这种情况,我想在开头将b *替换为<b>,在结尾将*替换为</b>(忽略反斜杠,以便在SO网站上转义)。

此外,可能有不止一场比赛:

b*any string here* and after that b*string b*.

这些情况不应该处理:

b*foo bar
foo bar*
bb*foo bar* (b is not after a whitespace or beginning of string).

我已经走了这么远:

(?<=b\*)(.*?)(?=\*)

这给了我介于两者之间的字符串,但是我在进行交换时遇到了困难。

2 个答案:

答案 0 :(得分:1)

使用String#replace,您只需捕获要保留的文本:

var result = theString.replace(/\bb\*(.*?)\*/g, "<b>$1</b>");

正则表达式开头的\b表示单词边界,因此它仅与不属于单词的b匹配。 $1表示第一个被捕获的组(.*?)

示例:

var str1 = "b*any string here* and after that b*string b*.";

var str2 = `b*foo bar
foo bar*
bb*foo bar* (b is not after a whitespace or beginning of string).`;

console.log(str1.replace(/\bb\*(.*?)\*/g, "<b>$1</b>"));

console.log(str2.replace(/\bb\*(.*?)\*/g, "<b>$1</b>"));

答案 1 :(得分:0)

您可以使用\b(?:b\*)(.+?)(?:\*),所以

const result = yourString.replace(/\b(?:b\*)(.+?)(?:\*)/, "<b>$1</b>");

请参见“替换”标签https://regexr.com/447cq