javascriptstringsplit

Split string with limit, where last string contains the remainder


e.g. if I run this javascript:

var str = 'hello_world_there';
var parts = str.split('_', 2);

var p1 = parts[0];
var p2 = parts[1];

at the end, p1 contains "hello", and p2 contains "world".

I'd like p1 to contain "hello", and p2 to contain "world_there". i.e. I want p2 to contain the rest of the string, regardless of how many underscores it has (similar to how c#'s String.Split(char[] separator, int count) behaves.

Any workarounds ?


Solution

  • var str = 'hello_world_there';
    var parts = str.split('_');
    
    var p1 = parts[0];
    var p2 = parts.slice(1).join('_');
    

    This will do an ordinary split, but then merge everything past the first match.