javascript - Replace all string occurrences - Stack Overflow

I want to replace all the occurrences of [h2][h2] in a JavaScript stringFor example, I havevar mystri

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745415545a4626730.html

相关推荐

  • javascript - Replace all string occurrences - Stack Overflow

    I want to replace all the occurrences of [h2][h2] in a JavaScript stringFor example, I havevar mystri

    1天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信