Javascript and regex: split string and keep the separator

后端 未结 7 2266
轮回少年
轮回少年 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 06:10

    If you wrap the delimiter in parantheses it will be part of the returned array.

    string.split(/(
    &#?[a-zA-Z0-9]+);/g); // returns ["aaaaaa", "
    †", "bbbb", "
    ‡", "cccc"]

    Depending on which part you want to keep change which subgroup you match

    string.split(/(
    )&#?[a-zA-Z0-9]+;/g); // returns ["aaaaaa", "
    ", "bbbb", "
    ", "cccc"]

    You could improve the expression by ignoring the case of letters string.split(/()&#?[a-z0-9]+;/gi);

    And you can match for predefined groups like this: \d equals [0-9] and \w equals [a-zA-Z0-9_]. This means your expression could look like this.

    string.split(/
    (&#?[a-z\d]+;)/gi);

    There is a good Regular Expression Reference on JavaScriptKit.

提交回复
热议问题