Reputation: 4733
I was trying to remove the "["or "]" pattern present in a string.
var str = "abc<1<2<>3>4>def";
while (str != (str = str.replace(/<[^<>]*>/g, "")));
using the above code which is removing "<" "<>" ">" pattern when i try to replace this with my operators it does'nt work .
any ways can any one provide me any regex or small one liner to replace all the operator present.
For ex a= [1[2]3][4
should be after removing 1234
or
a =1[2]3]
should be after removing 123
Upvotes: 1
Views: 4651
Reputation: 9664
This should work for you
var str = "abc[1[2[]3]4]def";
while (str != (str = str.replace(/\[[^\[\]]*\]/g, "")));
str
becomes abcdef
recursively removing all the enclosed text between []
. This would work only if the square brackets are balanced.
You can use this regex if you need to remove all the brackets
var str = str.replace(/]|\[/g, "");
Upvotes: 1
Reputation: 337627
var str = "abc[1[2[]3]4]def".replace(/\[|\]/g, "");
Your while condition is not required here as the regex will remove all instances of [
and ]
it finds due to the g
global parameter.
Upvotes: 4
Reputation: 93026
What about just
s = "[1[2]3][4"
s = s.replace(/[[\]]/g, "")
gives you the output
1234
Upvotes: 1