Skip to content

Instantly share code, notes, and snippets.

@john-doherty
Last active March 28, 2024 01:31
Show Gist options
  • Save john-doherty/0edb4fcbc1e51355e8b7b94f94ea54f0 to your computer and use it in GitHub Desktop.
Save john-doherty/0edb4fcbc1e51355e8b7b94f94ea54f0 to your computer and use it in GitHub Desktop.
Remove empty values, trim whitespace and removes duplicate from a comma separated string in JavaScript
/**
* Removes empty values, trims whitespace and removes duplicate from a comma separated string in JavaScript
* @example
* cleanCsvString('one, ,, , two,two,two, three'); // returns 'one,two,three'
* cleanCsvString('one, ,, , two,two,two, three', false); // returns 'one,two,two,two,three'
* @param {string} str - string to modify
* @param {boolean} removeDuplicates - should remove duplicate items? (default = true)
* @returns {string} cleaned CSV string
*/
function cleanCsvString(str, removeDuplicates) {
// default to true
removeDuplicates = (removeDuplicates === undefined) ? true : removeDuplicates;
// go through each item
return String(str).split(',').map(function(item) {
// trim value
return String(item).trim();
})
.filter(function(item, index, all) {
if (removeDuplicates) {
// remove empty items & duplicate values
return (item !== '') && (index === all.indexOf(item));
}
return item;
})
.join(',');
}
@john-doherty
Copy link
Author

cleanCsvString('one, ,, , two,two,two, three'); returns 'one,two,three'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment