JSFiddle - React, Tailwind, and code Playground
Split query by comma
by tonytlwu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
CSS
body {
background: #1f2227;
}
JavaScript
function splitByCommas(str) {
if (str === undefined || str === null) {
return [];
}
if (_.isArray(str)) {
return _.flatten(_.map(str, splitByCommas));
}
if (typeof str !== 'string') {
return [str];
}
// Split a string by commas but ignore commas within double-quotes
// Turn values within square brackets into a nested array
// Adapted from: https://stackoverflow.com/questions/11456850/split-a-string-by-commas-but-ignore-commas-within-double-quotes-using-javascript
var csvArrayPattern = /(".*?"|\[.*?\]|[^",\[\]]+)(?=\s*,|\s*$)/g;
var arrayPattern = /^(?:\[[\w\W]*\])$/;
var arr = [];
var res = csvArrayPattern.exec(str);
while (res !== null) {
if (arrayPattern.test(res[0])) {
arr.push(splitByCommas(res[0].replace(/(?:^\[)|(?:\]$)/g, '').trim()));
} else {
arr.push(res[0].replace(/(?:^")|(?:"$)/g, '').trim());
}
res = csvArrayPattern.exec(str);
}
return _.filter(_.map(arr, function (value) {
if (_.isArray(value)) {
return value;
}
return ('' + value).trim();
}), function (value) {
return _.isArray(value) || [undefined, null, '', NaN].indexOf(value) === -1;
});
}
function splitQueryValues(input) {
if (_.isNil(input)) {
return input;
}
return splitByCommas(input);
}
/* Tests */
function test(name, input, expected, fn, run) {
if (run === false) {
return;
}
var group = [];
var actual = fn(_.clone(input));
var pass = _.isMatch(actual, expected);
group.push(pass ? '✅' : '❌');
group.push(name);
var args = [input, actual];
console[pass ? 'groupCollapsed' : 'group'].apply(this, group);
console.log.apply(this, args);
console.groupEnd();
}
console.clear();
test(
'Separate by comma',
'Foo,Bar',
['Foo', 'Bar'],
splitQueryValues
);
test(
'Ignores commas wrapped in ""',
' Foo, "Adams, John" , Bar ',
['Foo', 'Adams, John', 'Bar'],
splitQueryValues
);
test(
'Parse arrays wrapped in []',
'Foo, [Foo,Bar], Bar',
...