Mango Mango - 1 year ago 59
Javascript Question

How do I split runs of alpha characters and numeric characters in a string?

I have a array that looks something like this:

var things = ["33bn", "2x", "Apple123"];

How can I convert that array into this:

var things = ["33", "bn", "2", "x", "Apple", "123"];

Would it be possible to do this with split and RegExp?

I'm not sure as to how I should do this, maybe I could loop through the array and split each item using RegExp then push each item of the new array into the old one?

Answer Source

You could use .reduce like this:

var things = ["33bn", "2x", "Apple123"];

things.reduce(function(item, i){
  return item.concat(i.match(/\d+|[A-Za-z]+/g));
}, []);