Split string with a single occurence (not twice) of a delimiter in Javascript

Viewed 1940

This is better explained with an example. I want to achieve an split like this:

two-separate-tokens-this--is--just--one--token-another

->

["two", "separate", "tokens", "this--is--just--one--token", "another"]

I naively tried str.split(/-(?!-)/) and it won't match the first occurrence of double delimiters, but it will match the second (as it is not followed by the delimiter):

["two", "separate", "tokens", "this-", "is-", "just-", "one-", "token", "another"]

Do I have a better alternative than looping through the string?

By the way, the next step should be replacing the two consecutive delimiters by just one, so it's kind of escaping the delimiter by repeating it... So the final result would be this:

["two", "separate", "tokens", "this-is-just-one-token", "another"]

If that can be achieved in just one step, that should be really awesome!

6 Answers
Related