Peter Olson
Peter Olson

Reputation: 143037

Split string with inner and outer delimeters in Javascript

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","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?

Upvotes: 1

Views: 161

Answers (2)

Yuriy Nemtsov
Yuriy Nemtsov

Reputation: 3915

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"]

Upvotes: 1

alex
alex

Reputation: 490667

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.

Upvotes: 3

Related Questions