In my Javascript code, I have a string that is something like this:
"1943[15]43[67]12[32]"
I want to return an array like this:
["1","9","4","3","15"开发者_如何学JAVA,"4","3","67","1", 2","32"]
That is, I want it to separate every character, except the numbers inside the brackets, which I want to preserve as one element.
Is there an elegant way to do this?
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.
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"]
精彩评论