Link to home
Start Free TrialLog in
Avatar of tbaseflug
tbaseflugFlag for United States of America

asked on

JavaScript - Everything to the left and right of "-"

I need to break apart a string - if it contains a "-"
Then I need to get one value with everything to the left of the dash and then another, with everything to the right of the dash?
Avatar of kaufmed
kaufmed
Flag of United States of America image

Something like this?

var hyphenIndex = str.indexOf("-");

if (hyphenIndex >= 0)
{
    var left = str.substring(0, hyphenIndex);
    var right = str.substring(hyphenIndex + 1);
}

Open in new window

You could also use split:

var str = 'something - something_else';
var substr = str.split('-');
// substr[0] contains "something"
// substr[1] contains "something_else"

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If there were more than one hyphen, your array will hold that many more substrings.

var str = 'something - something_else - and another thing';
var substr = str.split('-');
// substr[0] contains "something"
// substr[1] contains "something_else"
// substr[2] contains "and another thing"

Open in new window


Also, you can check if there is a hyphen to begin with. I did not include that code. You can do that kaufmed's way, or use a regex, it's up to you...
and just to clarify, if there was no hyphen substr[0] would return the original string.

also, using split, you can retrieve the length of the substring array and display that many results using a for loop.