Avatar of tbaseflug
Flag 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?
JavaScriptScripting LanguagesAJAX

Avatar of undefined
Last Comment
Kyle Hamilton

8/22/2022 - Mon

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 Hamilton

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


Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Kyle Hamilton

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...
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Kyle Hamilton

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.