How do I split a string with multiple separators in javascript?

前端 未结 22 1863
走了就别回头了
走了就别回头了 2020-11-21 23:14

How do I split a string with multiple separators in JavaScript? I\'m trying to split on both commas and spaces but, AFAIK, JS\'s split function only supports one separator.

22条回答
  •  深忆病人
    2020-11-21 23:33

    Here is a new way to achieving same in ES6:

    function SplitByString(source, splitBy) {
      var splitter = splitBy.split('');
      splitter.push([source]); //Push initial value
    
      return splitter.reduceRight(function(accumulator, curValue) {
        var k = [];
        accumulator.forEach(v => k = [...k, ...v.split(curValue)]);
        return k;
      });
    }
    
    var source = "abc,def#hijk*lmn,opq#rst*uvw,xyz";
    var splitBy = ",*#";
    console.log(SplitByString(source, splitBy));

    Please note in this function:

    • No Regex involved
    • Returns splitted value in same order as it appears in source

    Result of above code would be:

提交回复
热议问题