Reputation: 17530
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, "");
Upvotes: 5
Views: 428
Reputation: 227310
You need to escape the square braces.
var mystring = 'hii[h2][/h2]';
let string = mystring.replace(/\[h2\]\[\/h2\]/g, '');
console.log(string);
Upvotes: 8
Reputation: 69047
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,"");
Upvotes: 2
Reputation: 175956
Assuming nothing between those tags, you need to escape the []
also.
mystring.replace(/\[h2]\[\/h2]/g, "");
Upvotes: 2