[英]Split string into array using regular expression “[element1][element2]”
I have the following string: 我有以下字符串:
var search = "[title|Asc][description|Desc]";
I'd like an array of: 我想要一系列:
[
"title|Asc",
"description|Desc"
]
I've tried various reg ex, but i just don't understand it enough. 我已经尝试过各种reg ex,但我只是不太了解。
var matches = search.split(/[^a-zA-Z0-9|]/);
Any chance i can have some help? 有机会我可以帮忙吗?
Use split
and filter
使用
split
和filter
var output = search.split(/[\[\]]+/).filter( s => s.length > 0 );
Demo 演示
var search = "[title|Asc][description|Desc]"; var output = search.split(/[\\[\\]]+/).filter( s => s.length > 0 ); console.log(output);
Explanation 说明
split
by /[\\[\\]]+/
, which is a one or more occurrence of character class of []
用
/[\\[\\]]+/
split
,这是[]
字符类的一次或多次出现
filter
out empty items. filter
掉空项目。
Remove the first and last [
, ]
and then split by ][
删除第一个和最后一个
[
, ]
,然后按][
]
分割
search.substring(1,search.length-1).split('][')
var search = "[title|Asc][description|Desc]"; console.log(search.substring(1,search.length-1).split(']['))
It is better to use a match
instead of split
to make sure we match string between [
and ]
: 最好使用
match
而不是split
来确保我们匹配[
和]
之间的字符串:
const regex = /\\[([^\\]]*)\\]/g; const str = `[title|Asc][description|Desc]`; let m; while ((m = regex.exec(str)) !== null) { console.log(m[1]); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.