Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  24] [ 1]  / answers: 1 / hits: 18644  / 12 Years ago, tue, september 11, 2012, 12:00:00

is it possible to make a regex with multiple delimiters? For example I want to split a string which can come in two forms: 1. string1, string2, string3 or 2. string1,string2,string3. I've been trying to do this in javascript but with no success so far.


More From » regex

 Answers
35

Just use a regex split():



var string = part1,part2, part3, part4,    part5,
components = string.split(/,s*/);


JS Fiddle demo.



The reason I've used * rather than ? is simply because it allows for no white-space or many white-spaces. Whereas the ? matches zero-or-one white-space (which is exactly what you asked, but even so).



Incidentally, if there might possibly be white-spaces preceding the comma, then it might be worth amending the split() regex to:



var string = part1,part2  , part3, part4,    part5,
components = string.split(/s*,s*/);
console.log(components);​


JS Fiddle demo.



Which splits the supplied string on zero-or-more whitespace followed by a comma followed by zero-or-more white-space. This may, of course, be entirely unnecessary.



References:




[#83136] Monday, September 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
lara questions
;