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

tbaseflug
tbaseflug used Ask the Experts™
on
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?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
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

Kyle HamiltonData Scientist
Most Valuable Expert 2014

Commented:
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

Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
@kozaiwaniec
You could also use split:
...provided there's only one hyphen in the string  ; )

However, that code would fail if there were no hyphen in the string!
Kyle HamiltonData Scientist
Most Valuable Expert 2014

Commented:
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...
Kyle HamiltonData Scientist
Most Valuable Expert 2014

Commented:
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.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial