Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

javascript - How split a string in jquery with multiple strings as separator

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

var x = "Name: John Doe
Age: 30
Birth Date: 12/12/1981";
var pieces = x.split("
"), 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 "," 30 Birth "," 12/12/1981"
that x string is just an example and i dont have any string like that! how can i rewrite theses codes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do

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

This gives 3 strings :

["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 :

["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'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...