2

I'm trying to split a string into an array, where any numbers are split separately:

function mysplit(s) { ??? }

// What I want to have happen is this:
//
// mysplit('ABC12DEF678IJ') --> ['ABC',12,'DEF',678,'IJ']
// mysplit('ABCD123') --> ['ABCD',123]
// mysplit('Eeyore') --> ['Eeyore']

The only way I think I can do this is to use the function form of regex replace, using mutable state as the array, but that seems ugly. (See below TBD since that's the way I'm going to try to do it by default.)

Is there an easier way?

3 Answers 3

5

Using String.split() itself but with separator retention.

'ABC12DEF678IJ'.split(/(\d+)/);
["ABC", "12", "DEF", "678", "IJ"]

'ABCD123'.split(/(\d+)/)
["ABCD", "123", ""] //tiny issue. ;)

'Eeyore'.split(/(\d+)/)
["Eeyore"]

If separator contains capturing parentheses, matched results are returned in the array.

0
3

match can do it just fine:

function mysplit(s) {
    return s.match(/\d+|\D+/g);
}

No tiny issue :)

3
  • ooh ahh, I think we have a winner (will accept once the timeout is done)
    – Jason S
    Dec 12, 2012 at 17:08
  • Ooh, I like it except that I have to convert the string numbers to numbers.
    – Jason S
    Dec 12, 2012 at 17:21
  • @JasonS: If you get to use the ES5 array extensions: return s.match(/\d+|\D+/g).map(function(x) { var n = parseInt(x); return isNaN(n) ? x : n; });
    – Ry-
    Dec 12, 2012 at 17:23
1

For reference here is my original approach, it doesn't look too bad:

function numsplit(s)
{
    var a = [];
    s.replace(/([0-9]+)|([^0-9]+)/g, function(g) {
        a.push(isNaN(g) ? g : (+g));
    });
    return a;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.