javascriptjqueryregex

split string only on first instance of specified character


In my code I split a string based on _ and grab the second item in the array.

var element = $(this).attr('class');
var field = element.split('_')[1];

Takes good_luck and provides me with luck. Works great!

But, now I have a class that looks like good_luck_buddy. How do I get my javascript to ignore the second _ and give me luck_buddy?

I found this var field = element.split(new char [] {'_'}, 2); in a c# stackoverflow answer but it doesn't work. I tried it over at jsFiddle...


Solution

  • Use capturing parentheses:

    'good_luck_buddy'.split(/_(.*)/s)
    ['good', 'luck_buddy', ''] // ignore the third element
    

    They are defined as

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

    So in this case we want to split at _.* (i.e. split separator being a sub string starting with _) but also let the result contain some part of our separator (i.e. everything after _).

    In this example our separator (matching _(.*)) is _luck_buddy and the captured group (within the separator) is luck_buddy. Without the capturing parenthesis the luck_buddy (matching .*) would've not been included in the result array as it is the case with simple split that separators are not included in the result.

    We use the s regex flag to make . match on newline (\n) characters as well, otherwise it would only split to the first newline.