在我的Javascript代码中,我有一个类似这样的字符串:
"1943[15]43[67]12[32]"
我想返回一个这样的数组:
["1","9","4","3","15","4","3","67","1", 2","32"]
也就是说,我希望它将每个字符分开,但括号内的数字除外,我想将其保留为一个元素。
有优雅的方法吗?
答案 0 :(得分:3)
var str = '1943[15]43[67]12[32]',
matches = str.match(/\d|\[\d+\]/g);
for (var i = 0, matchesLength = matches.length; i < matchesLength; i++) {
matches[i] = matches[i].replace(/\D/g, '');
};
console.log(matches);
// ["1", "9", "4", "3", "15", "4", "3", "67", "1", "2", "32"]
答案 1 :(得分:1)
var str = "1943[15]43[67]12[32]",
re = new RegExp(/(\d)|\[(\d+)\]/g),
out = [],
m;
while (m = re.exec(str)) {
out.push(m[2] || m[0]);
}
console.log(out); // ["1", "9", "4", "3", "15", "4", "3", "67", "1", "2", "32"]