Javascript and regex: split string and keep the separator

后端 未结 7 2338
轮回少年
轮回少年 2020-11-22 05:25

I have a string:

var string = \"aaaaaa
† bbbb
‡ cccc\"

And I would like to split this string w

7条回答
  •  无人共我
    2020-11-22 05:58

    I was having similar but slight different problem. Anyway, here are examples of three different scenarios for where to keep the deliminator.

    "1、2、3".split("、") == ["1", "2", "3"]
    "1、2、3".split(/(、)/g) == ["1", "、", "2", "、", "3"]
    "1、2、3".split(/(?=、)/g) == ["1", "、2", "、3"]
    "1、2、3".split(/(?!、)/g) == ["1、", "2、", "3"]
    "1、2、3".split(/(.*?、)/g) == ["", "1、", "", "2、", "3"]
    

    Warning: The fourth will only work to split single characters. ConnorsFan presents an alternative:

    // Split a path, but keep the slashes that follow directories
    var str = 'Animation/rawr/javascript.js';
    var tokens = str.match(/[^\/]+\/?|\//g);
    

提交回复
热议问题