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

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

    I will provide a classic implementation for a such function. The code works in almost all versions of JavaScript and is somehow optimum.

    • It doesn't uses regex, which is hard to maintain
    • It doesn't uses new features of JavaScript
    • It doesn't uses multiple .split() .join() invocation which require more computer memory

    Just pure code:

    var text = "Create a function, that will return an array (of string), with the words inside the text";
    
    println(getWords(text));
    
    function getWords(text)
    {
        let startWord = -1;
        let ar = [];
    
        for(let i = 0; i <= text.length; i++)
        {
            let c = i < text.length ? text[i] : " ";
    
            if (!isSeparator(c) && startWord < 0)
            {
                startWord = i;
            }
    
            if (isSeparator(c) && startWord >= 0)
            {
                let word = text.substring(startWord, i);
                ar.push(word);
    
                startWord = -1;
            }
        }
    
        return ar;
    }
    
    function isSeparator(c)
    {
        var separators = [" ", "\t", "\n", "\r", ",", ";", ".", "!", "?", "(", ")"];
        return separators.includes(c);
    }
    

    You can see the code running in playground: https://codeguppy.com/code.html?IJI0E4OGnkyTZnoszAzf

提交回复
热议问题