我如何分裂一个字符串与多个分隔符在JavaScript?
我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。
我如何分裂一个字符串与多个分隔符在JavaScript?
我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。
当前回答
下面是使用Regex可能会有帮助的一些情况:
\W匹配其他任何字符[a-zA-Z0-9_]。例子:
("Hello World,I-am code").split(/\W+/); // would return [ 'Hello', 'World', 'I', 'am', 'code' ]
一个或多个空格 \d来匹配数字 如果你想用一些字符来分割,你可以使用str.split(/[,-]+/)
其他回答
a = "a=b,c:d"
array = ['=',',',':'];
for(i=0; i< array.length; i++){ a= a.split(array[i]).join(); }
这将返回没有特殊字符的字符串。
我用缩减和过滤解决了这个问题。它可能不是最易读的解决方案,也不是最快的,在现实生活中,我可能会在这里使用aaron的答案,但写起来很有趣。
[' ','_','-','.',',',':','@'].reduce(
(segs, sep) => segs.reduce(
(out, seg) => out.concat(seg.split(sep)), []),
['E-mail Address: user@domain.com, Phone Number: +1-800-555-0011']
).filter(x => x)
或作为一个函数:
function msplit(str, seps) {
return seps.reduce((segs, sep) => segs.reduce(
(out, seg) => out.concat(seg.split(sep)), []
), [str]).filter(x => x);
}
这将输出:
['E','mail','Address','user','domain','com','0','Phone','Number','+1','800','555','0011']
如果没有最后的过滤器,你将在数组中得到空字符串,其中两个不同的分隔符彼此相邻。
在Github上查看我的简单库
如果你真的不想访问或与repo交互,下面是工作代码:
/**
*
* @param {type} input The string input to be split
* @param {type} includeTokensInOutput If true, the tokens are retained in the splitted output.
* @param {type} tokens The tokens to be employed in splitting the original string.
* @returns {Scanner}
*/
function Scanner(input, includeTokensInOutput, tokens) {
this.input = input;
this.includeTokensInOutput = includeTokensInOutput;
this.tokens = tokens;
}
Scanner.prototype.scan = function () {
var inp = this.input;
var parse = [];
this.tokens.sort(function (a, b) {
return b.length - a.length; //ASC, For Descending order use: b - a
});
for (var i = 0; i < inp.length; i++) {
for (var j = 0; j < this.tokens.length; j++) {
var token = this.tokens[j];
var len = token.length;
if (len > 0 && i + len <= inp.length) {
var portion = inp.substring(i, i + len);
if (portion === token) {
if (i !== 0) {//avoid empty spaces
parse[parse.length] = inp.substring(0, i);
}
if (this.includeTokensInOutput) {
parse[parse.length] = token;
}
inp = inp.substring(i + len);
i = -1;
break;
}
}
}
}
if (inp.length > 0) {
parse[parse.length] = inp;
}
return parse;
};
用法很简单:
var tokens = new Scanner("ABC+DE-GHIJK+LMNOP", false , new Array('+','-')).scan();
console.log(tokens);
给:
['ABC', 'DE', 'GHIJK', 'LMNOP']
如果您希望在输出中包含分隔令牌(+和-),将false设置为true,瞧!它仍然有效。
现在的用法是:
var tokens = new Scanner("ABC+DE-GHIJK+LMNOP", true , new Array('+','-')).scan();
and
console.log(tokens);
将:
['ABC', '+', 'DE', '-', 'GHIJK', '+', 'LMNOP']
享受吧!
我很惊讶没有人建议它,但我的hack-ey(疯狂的快速)解决方案是附加几个“替换”调用之前由相同的字符分裂。
即删除a, b, c, d和e:
let str = 'afgbfgcfgdfgefg'
let array = str.replace('a','d').replace('b','d').replace('c','d').replace('e','d').split('d')
这可以方便地概括为一个拆分器数组,如下:
function splitByMany( manyArgs, string ) {
do {
let arg = manyArgs.pop()
string = string.replace(arg, manyArgs[0])
} while (manyArgs.length > 2)
return string.split(manyArgs[0])
}
因此,在您的情况下,您可以调用
let array = splitByMany([" ", ","], 'My long string containing commas, and spaces, and more commas');
我使用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"]