如何将jquery中的字符串与多个字符串拆分为分隔符

时间:2012-12-13 19:41:52

标签: javascript jquery regex string split

我想在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字符串只是一个例子,我没有这样的字符串! 我怎么能重写这些代码?

2 个答案:

答案 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"]