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.

Sign up to request clarification or add additional context in comments.

Comments

3

match can do it just fine:

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

No tiny issue :)

3 Comments

ooh ahh, I think we have a winner (will accept once the timeout is done)
Ooh, I like it except that I have to convert the string numbers to numbers.
@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; });
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;
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.