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

前端 未结 6 1434
星月不相逢
星月不相逢 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条回答
  •  猫巷女王i
    2020-12-18 05:41

    I don't know how to do it purely with the regex engine in JS. You could do it this way that is a little less involved than manually parsing:

    var str = "two-separate-tokens-this--is--just--one--token-another";
    str = str.replace(/--/g, "#!!#");
    var split = str.split(/-/);
    for (var i = 0; i < split.length; i++) {
        split[i] = split[i].replace(/#!!#/g, "--");
    }
    

    Working demo: http://jsfiddle.net/jfriend00/hAhAB/

提交回复
热议问题