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

前端 未结 22 1550
走了就别回头了
走了就别回头了 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<str.length;i++){
            if (hashSet.has(str[i])){
                result.push(str.substring(lastIndex,i));
                lastIndex = i+1;
            }
        }
        result.push(str.substring(lastIndex));
        return result;
    }
    
    multiSplit('1,2,3.4.5.6 7 8 9',[',','.',' ']);
    // Output: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    
    multiSplit('1,2,3.4.5.6 7 8 9',' ');
    // Output: ["1,2,3.4.5.6", "7", "8", "9"]
    
    0 讨论(0)
  • 2020-11-21 23:55

    My refactor of @Brian answer

    var string = 'and this is some kind of information and another text and simple and some egample or red or text';
    var separators = ['and', 'or'];
    
    function splitMulti(str, separators){
                var tempChar = 't3mp'; //prevent short text separator in split down
                
                //split by regex e.g. \b(or|and)\b
                var re = new RegExp('\\b(' + separators.join('|') + ')\\b' , "g");
                str = str.replace(re, tempChar).split(tempChar);
                
                // trim & remove empty
                return str.map(el => el.trim()).filter(el => el.length > 0);
    }
    
    console.log(splitMulti(string, separators))

    0 讨论(0)
  • 2020-11-21 23:56

    Pass in a regexp as the parameter:

    js> "Hello awesome, world!".split(/[\s,]+/)
    Hello,awesome,world!
    

    Edited to add:

    You can get the last element by selecting the length of the array minus 1:

    >>> bits = "Hello awesome, world!".split(/[\s,]+/)
    ["Hello", "awesome", "world!"]
    >>> bit = bits[bits.length - 1]
    "world!"
    

    ... and if the pattern doesn't match:

    >>> bits = "Hello awesome, world!".split(/foo/)
    ["Hello awesome, world!"]
    >>> bits[bits.length - 1]
    "Hello awesome, world!"
    
    0 讨论(0)
  • 2020-11-21 23:58

    You can pass a regex into Javascript's split operator. For example:

    "1,2 3".split(/,| /) 
    ["1", "2", "3"]
    

    Or, if you want to allow multiple separators together to act as one only:

    "1, 2, , 3".split(/(?:,| )+/) 
    ["1", "2", "3"]
    

    (You have to use the non-capturing (?:) parens because otherwise it gets spliced back into the result. Or you can be smart like Aaron and use a character class.)

    (Examples tested in Safari + FF)

    0 讨论(0)
提交回复
热议问题