0

问题:我想获取所有方括号的内容,然后删除它们,但前提是方括号位于字符串的开头。

例如,给定字符串[foo][asd][dsa] text text text将返回包含所有三个括号内容 ( ["foo", "asd", "dsa"]) 的数组,字符串将变为text text text.

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

我怎样才能使用 JavaScript 做到这一点?

4

3 回答 3

1

您可以继续使用一段时间,首先将其添加到数组中,然后将其删除,然后再次执行所有操作。这将给出:

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
于 2013-04-15T10:18:48.867 回答
1

循环检查字符串的开头是否有方括号中的任何内容,获取方括号的内容,并从开头删除全部内容。

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 */
}
于 2013-04-15T10:13:34.177 回答
1

就像是var newstring = oldstring.replace(/\[\w{3}]/, "");

于 2013-04-15T09:42:28.873 回答