最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - recursively remove "[" and "]" pattern in a string using javascript - Stack Overflo

programmeradmin0浏览0评论

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

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
Share Improve this question asked Nov 8, 2011 at 10:12 ankurankur 4,74315 gold badges67 silver badges104 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4
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.

What about just

s = "[1[2]3][4"
s = s.replace(/[[\]]/g, "")

gives you the output

1234

This should work for you

var str = "abc[1[2[]3]4]def";
while (str != (str = str.replace(/\[[^\[\]]*\]/g, ""))); 

str bees 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, "");
发布评论

评论列表(0)

  1. 暂无评论