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

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

提交回复
热议问题