How do I split a string with multiple separators in JavaScript? I\'m trying to split on both commas and spaces but, AFAIK, JS\'s split function only supports one separator.
An easy way to do this is to process each character of the string with each delimiter and build an array of the splits:
splix = function ()
{
u = [].slice.call(arguments); v = u.slice(1); u = u[0]; w = [u]; x = 0;
for (i = 0; i < u.length; ++i)
{
for (j = 0; j < v.length; ++j)
{
if (u.slice(i, i + v[j].length) == v[j])
{
y = w[x].split(v[j]); w[x] = y[0]; w[++x] = y[1];
};
};
};
return w;
};
console.logg = function ()
{
document.body.innerHTML += "
" + [].slice.call(arguments).join();
}
splix = function() {
u = [].slice.call(arguments);
v = u.slice(1);
u = u[0];
w = [u];
x = 0;
console.logg("Processing: " + JSON.stringify(w) + "");
for (i = 0; i < u.length; ++i) {
for (j = 0; j < v.length; ++j) {
console.logg("Processing: [\x22" + u.slice(i, i + v[j].length) + "\x22, \x22" + v[j] + "\x22]");
if (u.slice(i, i + v[j].length) == v[j]) {
y = w[x].split(v[j]);
w[x] = y[0];
w[++x] = y[1];
console.logg("Currently processed: " + JSON.stringify(w) + "\n");
};
};
};
console.logg("Return: " + JSON.stringify(w) + "");
};
setTimeout(function() {
console.clear();
splix("1.23--4", ".", "--");
}, 250);
@import url("http://fonts.googleapis.com/css?family=Roboto");
body {font: 20px Roboto;}
Usage:
splix(string, delimiters...)Example:
splix("1.23--4", ".", "--")Returns:
["1", "23", "4"]