Last active
March 28, 2024 01:31
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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(','); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cleanCsvString('one, ,, , two,two,two, three');
returns'one,two,three'