Javascript and regex: split string and keep the separator

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

    I've been using this:

    String.prototype.splitBy = function (delimiter) {
      var 
        delimiterPATTERN = '(' + delimiter + ')', 
        delimiterRE = new RegExp(delimiterPATTERN, 'g');
    
      return this.split(delimiterRE).reduce((chunks, item) => {
        if (item.match(delimiterRE)){
          chunks.push(item)
        } else {
          chunks[chunks.length - 1] += item
        };
        return chunks
      }, [])
    }
    

    Except that you shouldn't mess with String.prototype, so here's a function version:

    var splitBy = function (text, delimiter) {
      var 
        delimiterPATTERN = '(' + delimiter + ')', 
        delimiterRE = new RegExp(delimiterPATTERN, 'g');
    
      return text.split(delimiterRE).reduce(function(chunks, item){
        if (item.match(delimiterRE)){
          chunks.push(item)
        } else {
          chunks[chunks.length - 1] += item
        };
        return chunks
      }, [])
    }
    

    So you could do:

    var haystack = "aaaaaa
    † bbbb
    ‡ cccc" var needle = '
    &#?[a-zA-Z0-9]+;'; var result = splitBy(haystack , needle) console.log( JSON.stringify( result, null, 2) )

    And you'll end up with:

    [
      "
    † bbbb", "
    ‡ cccc" ]

提交回复
热议问题