我如何分裂一个字符串与多个分隔符在JavaScript?
我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。
我如何分裂一个字符串与多个分隔符在JavaScript?
我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。
当前回答
你可以将一个正则表达式传递给JavaScript的split()方法。例如:
"1,2 3".split(/,| /)
["1", "2", "3"]
或者,如果你想让多个分隔符一起只起到一个作用:
"1, 2, , 3".split(/(?:,| )+/)
["1", "2", "3"]
您必须使用非捕获(?:)括号,因为 否则它会被拼接回结果中。或者你可以聪明一点 比如Aaron,使用一个角色类。
在Safari和Firefox中测试的示例。
其他回答
您可以将所有想要单独或共同用作分隔符的字符合并到一个正则表达式中,并将它们传递给split函数。例如,你可以这样写:
console.log( "dasdnk asd, (naks) :d skldma".split(/[ \(,\)]+/) );
输出将是:
["dasdnk", "asd", "naks", ":d", "skldma"]
从@stephen-sweriduk解决方案开始(这对我来说更有趣!),我对它进行了轻微的修改,使其更加通用和可重用:
/**
* Adapted from: http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
*/
var StringUtils = {
/**
* Flatten a list of strings
* http://rosettacode.org/wiki/Flatten_a_list
*/
flatten : function(arr) {
var self=this;
return arr.reduce(function(acc, val) {
return acc.concat(val.constructor === Array ? self.flatten(val) : val);
},[]);
},
/**
* Recursively Traverse a list and apply a function to each item
* @param list array
* @param expression Expression to use in func
* @param func function of (item,expression) to apply expression to item
*
*/
traverseListFunc : function(list, expression, index, func) {
var self=this;
if(list[index]) {
if((list.constructor !== String) && (list[index].constructor === String))
(list[index] != func(list[index], expression)) ? list[index] = func(list[index], expression) : null;
(list[index].constructor === Array) ? self.traverseListFunc(list[index], expression, 0, func) : null;
(list.constructor === Array) ? self.traverseListFunc(list, expression, index+1, func) : null;
}
},
/**
* Recursively map function to string
* @param string
* @param expression Expression to apply to func
* @param function of (item, expressions[i])
*/
mapFuncToString : function(string, expressions, func) {
var self=this;
var list = [string];
for(var i=0, len=expressions.length; i<len; i++) {
self.traverseListFunc(list, expressions[i], 0, func);
}
return self.flatten(list);
},
/**
* Split a string
* @param splitters Array of characters to apply the split
*/
splitString : function(string, splitters) {
return this.mapFuncToString(string, splitters, function(item, expression) {
return item.split(expression);
})
},
}
然后
var stringToSplit = "people and_other/things";
var splitList = [" ", "_", "/"];
var splittedString=StringUtils.splitString(stringToSplit, splitList);
console.log(splitList, stringToSplit, splittedString);
归还原物的:
[ ' ', '_', '/' ] 'people and_other/things' [ 'people', 'and', 'other', 'things' ]
我发现我需要这样做的主要原因之一是在/和\上拆分文件路径。这是一个有点棘手的正则表达式,所以我将它贴在这里作为参考:
var splitFilePath = filePath.split(/[\/\\]/);
例如,如果你在String 07:05:45PM中使用了split and replace
var hour = time.replace("PM", "").split(":");
结果
[ '07', '05', '45' ]
让我们保持简单:(在你的RegEx中添加“[]+”表示“1或更多”)
这意味着“+”和“{1,}”是相同的。
var words = text.split(/[ .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/); // note ' and - are kept