split string only on first instance of specified character

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…

Solutions/Answers:

Solution 1:

Use capturing parentheses:

"good_luck_buddy".split(/_(.+)/)[1]
"luck_buddy"

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 lucky_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.

Related:  D3, nested appends, and data flow

Solution 2:

What do you need regular expressions and arrays for?

myString = myString.substring(myString.indexOf('_')+1)
var myString= "hello_there_how_are_you"
myString = myString.substring(myString.indexOf('_')+1)
console.log(myString)

Solution 3:

I avoid RegExp at all costs. Here is another thing you can do:

"good_luck_buddy".split('_').slice(1).join('_')

Solution 4:

Replace the first instance with a unique placeholder then split from there.

"good_luck_buddy".replace(/\_/,'&').split('&')

["good","luck_buddy"]

This is more useful when both sides of the split are needed.

Solution 5:

You can use the regular expression like:

var arr = element.split(/_(.*)/)


You can use the second parameter which specifies the limit of the split.
i.e:

var field = element.split(‘_’, 1)[1];

Solution 6:

Javascript’s String.split unfortunately has no way of limiting the actual number of splits. It has a second argument that specifies how many of the actual split items are returned, which isn’t useful in your case. The solution would be to split the string, shift the first item off, then rejoin the remaining items::

var element = $(this).attr('class');
var parts = element.split('_');

parts.shift(); // removes the first item from the array
var field = parts.join('_');

Related:  Can vue-router open a link in a new tab?