[英]Transform string with square brackets into list in where square bracket content is combined
I want to transform the following string: 我想转换以下字符串:
[test1 test2] test3 [test4 test5] test6 test7 [test8]
into the following array: 放入以下数组:
test1 test2, test3, test4 test5, test6, test7, test8
I have tried allot of things allready from $.grep to regEx. 我已经尝试从$ .grep到regEx分配所有东西。 But it's just not cutting it.
但这只是没有削减。 The closest I have come is the following:
我最接近的是以下内容:
var block_parts = text.match(/[^[\]]+(?=])/g);
var rest = text.replace(/ *\[[^\]]*]/g, '').split(" ");
var complete = $.merge(rest, block_parts);
But then it's not in the same order. 但这不是相同的顺序。 (it will attach block_parts after rest)
(休息后它将附加block_parts)
Does anybody have an idea how I can do this? 有人知道我该怎么做吗?
Use double replace function. 使用双重替换功能。
\\] +| +\\[
\\] +| +\\[
would match all the ]
plus the following one or more space and also the closing [
along with the preceding spaces. \\] +| +\\[
将匹配所有]
加以下一个或多个空格,以及结尾[
和前面的空格。 Just replace those matched characters with ,<space>
and again replace [
, ]
with an empty string. 只需将匹配的字符替换为
,<space>
然后再次将[
, ]
替换为空字符串。
> var s = "[test1 test2] test3 [test4 test5] test6 test7 [test8]"
undefined
> var m = s.replace(/\] +| +\[/g, ", ").replace(/[\[\]]/g,'')
undefined
> console.log(m)
test1 test2, test3, test4 test5, test6 test7, test8
Update: 更新:
> var m = s.replace(/\] +| +\[|\s+(?!\w+\])/g, ", ").replace(/[\[\]]/g,'')
undefined
> console.log(m)
test1 test2, test3, test4 test5, test6, test7, test8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.