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
3 Answers
Reset to default 8You 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,"");