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

前端 未结 6 1432
星月不相逢
星月不相逢 2020-12-18 05:04

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

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

->

6条回答
  •  太阳男子
    2020-12-18 05:19

    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.

提交回复
热议问题