jQuery正则表达式方括号

问题描述:

问题:我想获取所有方括号的内容,然后删除它们,但仅当括号位于字符串的beginnig时。jQuery正则表达式方括号

例如,[foo][asd][dsa] text text text将返回包含所有三个括号内容(0 => 'foo', 1 => 'asd', 2 => 'dsa')的数组,并且将变为text text text

但是,如果字符串看起来像这样:[foo] text [asd][dsa] text text,它将只需要[foo],字符串将是:text [asd][dsa] text text

我该怎么做? (使用JS或jQuery的)

感谢, 和对不起我的英语:\

循环检查字符串在方括号什么的开始,需要的内容括号,并从一开始就删除整个批次。

var haystack = "[foo][asd][dsa] text text text"; 
var needle = /^\[([^\]]+)\](.*)/; 
var result = new Array(); 

while (needle.test(haystack)) { /* while it starts with something in [] */ 
    result.push(needle.exec(haystack)[1]);  /* get the contents of [] */ 
    haystack = haystack.replace(needle, "$2"); /* remove [] from the start */ 
} 
+0

谢谢!很棒! – HtmHell

+0

我还有一个问题。如果我想使用另一个符号,例如:'>',我应该改变什么? – HtmHell

+1

对于我的代码'var needle =/^ ] +)>>(。*)/;'但对于Brugnar的'var rule =/^(?: *)>>)/ g; – SpacedMonkey

喜欢的东西var newstring = oldstring.replace(/\[\w{3}]/, "");

+0

谢谢,我需要这个,但我需要一个数组与老字符串了。 例如,var [foo] [asd]文本文本将返回数组: ' 0 =>'foo', 1 =>'asd' ' – HtmHell

你可以继续使用一段时间,以第一,它添加到一个数组,删除它,然后做一次。这将给这个:

var t1 = "[foo][asd][dsa] text text text"; 
var rule = /^(?:\[([^\]]*)\])/g; 
var arr = new Array(); 

while(m = rule.exec(t1)){ 
    arr.push(m[1]); 
    t1 = t1.replace(rule, "") 
} 

alert(arr); // foo,asd,dsa 
alert(t1); // text text text