Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 985
fortran Avatar asked Aug 13 '12 18:08

fortran


1 Answers

str.match(/(?!-)(.*?[^\-])(?=(?:-(?!-)|$))/g);

Check this fiddle.


Explanation:

Non-greedy pattern (?!-)(.*?[^\-]) match a string that does not start and does not end with dash character and pattern (?=(?:-(?!-)|$)) requires such match to be followed by single dash character or by end of line. Modifier /g forces function match to find all occurrences, not just a single (first) one.


Edit (based on OP's comment):

str.match(/(?:[^\-]|--)+/g);

Check this fiddle.

Explanation:

Pattern (?:[^\-]|--) will match non-dash character or double-dash string. Sign + says that such matching from the previous pattern should be multiplied as many times as can. Modifier /g forces function match to find all occurrences, not just a single (first) one.

Note:

Pattern /(?:[^-]|--)+/g works in Javascript as well, but JSLint requires to escape - inside of square brackets, otherwise it comes with error.

like image 163
Ωmega Avatar answered Sep 22 '22 12:09

Ωmega