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

前端 未结 22 1582
走了就别回头了
走了就别回头了 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:54

    I don't know the performance of RegEx, but here is another alternative for RegEx leverages native HashSet and works in O( max(str.length, delimeter.length) ) complexity instead:

    var multiSplit = function(str,delimiter){
        if (!(delimiter instanceof Array))
            return str.split(delimiter);
        if (!delimiter || delimiter.length == 0)
            return [str];
        var hashSet = new Set(delimiter);
        if (hashSet.has(""))
            return str.split("");
        var lastIndex = 0;
        var result = [];
        for(var i = 0;i

提交回复
热议问题