[英]JavaScript: How to split string into array based on a curly-braces-pattern?
I want to split a string similar to this:我想拆分一个类似于这样的字符串:
"2*{some_string}*8*{some_other_string}"
Into an array, keeping the curly braces intact:放入一个数组中,保持花括号完整:
["2*","{some_string}","*8*","{some_other_string}"]
I'm hitting a wall and always end up remove the curly braces.我碰壁了,最后总是去掉花括号。 Any clues out there?
有什么线索吗?
I've been working with something like this:我一直在处理这样的事情:
var found = [], // an array to collect the strings that are found
rxp = /{([^}]+)}/g,
str = "a {string} with {curly} braces",
curMatch;
while( curMatch = rxp.exec( str ) ) {
found.push( curMatch[1] );
}
console.log( found ); // ["string", "curly"]
Thanks:)谢谢:)
Don't really need replace.真的不需要更换。 You can keep the {} when you split it by using regex, but it will create empty string, so you will need to use filter to remove empty string in the array after splitting.
使用正则表达式拆分时可以保留{},但它会创建空字符串,因此您需要使用过滤器删除拆分后数组中的空字符串。
console.log("2*{some_string}*8*{some_other_string}".split(/({.*?})/).filter(s => !!s))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.