5

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, "");
Cœur
  • 37,241
  • 25
  • 195
  • 267
Sourav
  • 17,065
  • 35
  • 101
  • 159
  • 5
    `[` is a special character, you'd need to escape it too. – pimvdb May 20 '11 at 15:55
  • Possible duplicate of [How to replace all dots in a string using JavaScript](http://stackoverflow.com/q/2390789/1529630), but here with brackets instead of dots. – Oriol Oct 10 '15 at 23:39

3 Answers3

8

You need to escape the square braces.

var mystring = 'hii[h2][/h2]';
let string = mystring.replace(/\[h2\]\[\/h2\]/g, '');
console.log(string);
mitesh7172
  • 666
  • 1
  • 11
  • 21
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
2

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

mystring.replace(/\[h2]\[\/h2]/g, "");
Alex K.
  • 171,639
  • 30
  • 264
  • 288
2

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,"");
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
sergio
  • 68,819
  • 11
  • 102
  • 123