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.
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:
string.split()
.Yes, make the whitespace (\s
) optional using ?
:
var s = "string1,string2,string3";
s.split(/,\s?/);
In addition to silva
just in case you have doubt it can have more than one space then use (or no space)
var s = "string1, string2, string3";
s.split(/,\s*/);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With