Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string based on a symbol

I'm trying to split a string into an array based on the second occurrence of the symbol _

var string = "this_is_my_string";

I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.

In the example string above I would need it to be split like this.

var split = [this_is, _my_string];
like image 980
Chapsterj Avatar asked May 06 '26 12:05

Chapsterj


1 Answers

var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
             string.substring(secondUnderscore)];

Paste it into your browser's console to try it out. No need for a jsFiddle.

like image 91
Matt Ball Avatar answered May 09 '26 01:05

Matt Ball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!