javascript 如何在jquery中用多个字符串作为分隔符分割一个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13867182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:00:52  来源:igfitidea点击:

How split a string in jquery with multiple strings as separator

javascriptjqueryregexstringsplit

提问by SilverLight

i want to split a string in jquery or javascript with multiple separator.
for one string as separator we can have :

我想用多个分隔符在 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
}

But i want to split such that string(x) with : Age:and Date:(mean a string array as separator)
and at last i want a sting array with these parts : "Name: John Doe\n"," 30\nBirth "," 12/12/1981"
that x string is just an example and i dont have any string like that! how can i rewrite theses codes?

但我想用 :Age:Date:(意思是一个字符串数组作为分隔符)拆分字符串(x)
,最后我想要一个带有这些部分的字符串数组:“姓名:John Doe\n”、“30\nBirth”、“ 12/12/1981”
那个 x 字符串只是一个例子,我没有这样的字符串!我怎样才能重写这些代码?

回答by Denys Séguret

You can do

你可以做

var tokens = x.split(/Age:|Date:/g);

This gives 3 strings :

这给出了 3 个字符串:

["Name: John Doe
", " 30
Birth ", " 12/12/1981"]

If you want also to get the separators, use

如果您还想获得分隔符,请使用

var tokens = x.split(/(Age:|Date:)/g);

This gives 5 strings :

这给出了 5 个字符串:

["Name: John Doe
", "Age:", " 30
Birth ", "Date:", " 12/12/1981"]

If you want to build your regexp dynamically use

如果要动态构建正则表达式,请使用

var separators = ["Date:", "Age:"];
var tokens = x.split(new RegExp(separators.join('|'), 'g'));?????????????????

or

或者

var separators = ["Date:", "Age:"];
var tokens = x.split(new RegExp('('+separators.join('|')+')', 'g'));

回答by Travis Heeter

Here's a function based on one of @DenysSéguret's answers:

这是一个基于@DenysSéguret 答案之一的函数:

String.prototype.xSplit = function(separators){
    return this
      .split(new RegExp(separators.join('|'), 'g'))
      .map(function(bar){ return bar.trim() }); // remove trailing spaces
}

Usage:

用法:

var foo = "Before date Date: between date & age Age: after age";
foo = foo.xSplit(???????????????["Date:", "Age:"]);

Outcome:

结果:

foo == ["Before date", "between date & age", "after age"]