Search code examples

split string only at one single point

I my script I need to split a string from were the dash/hyphen is. And assign each piece to one variable.


Blue Oyster Cult - Don't Fear The Reaper
Jimi Hendrix - Come On (Let The Good Times Roll)
Molly Hatchet - Dreams I'll Never See

I think regex can do it with [\-]+ but I am looking for a method that it does not make more than two variables. So whatever string it takes, the outcome must be in only two pieces. I think the best approach is to consider only the first - (hyphen) in the string.

Any idea how to achieve this?

Thanks in advance.


  • Simply do .split(/-(.+)/)

    When splitting by -(.+) the matching group (.+) will get you the needed second part in its entirety, since .+ will consume all characters after the first - till the end of line:

    const text = "Hello world - This is super - easy and cool";
    const parts = text.split(/-(.+)/);
    console.log(parts[0].trim());      // "Hello world"
    console.log(parts[1].trim());      // "This is super - easy and cool"

    P.S: notice that above I use .trim() just to get rid of the string wrapping whitespaces for regex simplicity and demo!. Although, if parts[1] returns undefined, you'll get an error. So use wisely - or expand the regex to account for optional whitespaces before and after the separator - with \s?

    const text = "Hello world - This is super - easy and cool";
    const parts = text.split(/\s?-\s?(.+)/);
    console.log(parts[0]);      // "Hello world"
    console.log(parts[1]);      // "This is super - easy and cool"