最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace all string occurrences - Stack Overflow

programmeradmin1浏览0评论

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

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, "");
Share Improve this question edited Apr 30, 2017 at 12:54 Cœur 38.8k25 gold badges206 silver badges278 bronze badges asked May 20, 2011 at 15:54 SouravSourav 17.5k35 gold badges108 silver badges162 bronze badges 2
  • 5 [ is a special character, you'd need to escape it too. – pimvdb Commented May 20, 2011 at 15:55
  • Possible duplicate of How to replace all dots in a string using JavaScript, but here with brackets instead of dots. – Oriol Commented Oct 10, 2015 at 23:39
Add a ment  | 

3 Answers 3

Reset to default 8

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)

  1. 暂无评论