我想在jquery或javascript中拆分一个带有多个分隔符的字符串 我们可以将一个字符串作为分隔符:
var x = "Name: John Doe\nAge: 30\nBirth Date: 12/12/1981";
var pieces = x.split("\n"), part;
for (var i = 0; i < pieces.length; i++) {
bla bla bla
}
但是我希望将字符串(x)拆分为:Age:
和Date:
(表示字符串数组作为分隔符)
最后我想要一个带有这些部件的刺痛阵列:“名字:John Doe \ n”,“30 \ nBirth”,“12/12/1981”
那个x字符串只是一个例子,我没有这样的字符串!
我怎么能重写这些代码?
答案 0 :(得分:12)
你可以做到
var tokens = x.split(/Age:|Date:/g);
这给出了3个字符串:
["Name: John Doe
", " 30
Birth ", " 12/12/1981"]
如果您还想获得分隔符,请使用
var tokens = x.split(/(Age:|Date:)/g);
这给出了5个字符串:
["Name: John Doe
", "Age:", " 30
Birth ", "Date:", " 12/12/1981"]
如果要动态构建正则表达式,请使用
var separators = ["Date:", "Age:"];
var tokens = x.split(new RegExp(separators.join('|'), 'g'));
或
var separators = ["Date:", "Age:"];
var tokens = x.split(new RegExp('('+separators.join('|')+')', 'g'));
答案 1 :(得分:0)
这是一个基于@DenysSéguret答案之一的函数:
String.prototype.xSplit = function(separators){
return this
.split(new RegExp(separators.join('|'), 'g'))
.map(function(bar){ return bar.trim() }); // remove trailing spaces
}
用法:
var foo = "Before date Date: between date & age Age: after age";
foo = foo.xSplit(["Date:", "Age:"]);
结果:
foo == ["Before date", "between date & age", "after age"]