我如何分裂一个字符串与多个分隔符在JavaScript?

我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。


当前回答

传入一个regexp作为参数:

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

编辑补充:

你可以通过选择数组的长度减去1来获得最后一个元素:

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

... 如果模式不匹配:

>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"

其他回答

棘手的方法:

var s = "dasdnk asd, (naks) :d skldma";
var a = s.replace('(',' ').replace(')',' ').replace(',',' ').split(' ');
console.log(a);//["dasdnk", "asd", "naks", ":d", "skldma"]

我使用regexp:

str =  'Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".';

var strNew = str.match(/\w+/g);

// Output: ["Write", "a", "program", "that", "extracts", "from", "a", "given", "text", "all", "palindromes", "e", "g", "ABBA", "lamal", "exe"]

您可以将所有想要单独或共同用作分隔符的字符合并到一个正则表达式中,并将它们传递给split函数。例如,你可以这样写:

console.log( "dasdnk asd, (naks) :d skldma".split(/[ \(,\)]+/) );

输出将是:

["dasdnk", "asd", "naks", ":d", "skldma"]

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))

例如,如果你在String 07:05:45PM中使用了split and replace

var hour = time.replace("PM", "").split(":");

结果

[ '07', '05', '45' ]