开发者

Replace all string occurrences

I want to replace all the occurrences of [h2][/h2] in a JavaScript string For example, I have

var mystring = 'hii[h2][/h2]';

I want to get -> hii

so far I tried

mystring.replace(/[h2][\/h2]/g, "");开发者_开发知识库


You need to escape the square braces.

var mystring = 'hii[h2][/h2]';
let string = mystring.replace(/\[h2\]\[\/h2\]/g, '');
console.log(string);


Assuming nothing between those tags, you need to escape the [] also.

mystring.replace(/\[h2]\[\/h2]/g, "");


try this one:

str.replace(/\[h2\]\[\/h2\]/g,"");

note that you have to escape [ and ] if they form part of the text you want to replace otherwise they are interpreted as "character class" markers.

If the [h2] and [/h2] could also appear separate, you could use this one:

str.replace(/\[\/?h2\]/g,"");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜