4

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\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?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
SilverLight
  • 19,668
  • 65
  • 192
  • 300
  • 1
    Repeat....http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript – bobthyasian Dec 13 '12 at 19:45

2 Answers2

13

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'));
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

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

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"]
Travis Heeter
  • 13,002
  • 13
  • 87
  • 129