在我的Javascript代码中,我有一个像这样的字符串:
"1943[15]43[67]12[32]"
我想返回这样的数组:
["1","9","4","3","15","4","3","67","1", 2","32"]
也就是说,我希望它分隔每个字符,但括号内的数字除外,我想将其保留为一个元素。
有没有一种优雅的方法可以做到这一点?
最佳答案
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"]
jsFiddle。