Sourav
Sourav

Reputation: 17530

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

Upvotes: 5

Views: 428

Answers (3)

gen_Eric
gen_Eric

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

sergio
sergio

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

Alex K.
Alex K.

Reputation: 175956

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

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

Upvotes: 2

Related Questions