Javascript and regex: split string and keep the separator

后端 未结 7 2335
轮回少年
轮回少年 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:01

    answered it here also JavaScript Split Regular Expression keep the delimiter

    use the (?=pattern) lookahead pattern in the regex example

    var string = '500x500-11*90~1+1';
    string = string.replace(/(?=[$-/:-?{-~!"^_`\[\]])/gi, ",");
    string = string.split(",");
    

    this will give you the following result.

    [ '500x500', '-11', '*90', '~1', '+1' ]
    

    Can also be directly split

    string = string.split(/(?=[$-/:-?{-~!"^_`\[\]])/gi);
    

    giving the same result

    [ '500x500', '-11', '*90', '~1', '+1' ]
    

提交回复
热议问题