tbaseflug
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?
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?
You could also use split:
var str = 'something - something_else';
var substr = str.split('-');
// substr[0] contains "something"
// substr[1] contains "something_else"
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If there were more than one hyphen, your array will hold that many more substrings.
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...
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"
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.
also, using split, you can retrieve the length of the substring array and display that many results using a for loop.
Open in new window