Last active
March 31, 2021 00:48
-
-
Save vrymel/eb386e6aa4af371a9e1a792e33d219f4 to your computer and use it in GitHub Desktop.
Split inputs with multiple separators
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
const input = "a.com,b.com c.com\nwow.com"; | |
const outputSet = splitByMultipleSeparators(input); | |
const outputArray = Array.from(outputSet); // ['a.com', 'b.com', 'c.com', 'wow.com'] | |
function splitByMultipleSeparators(rawValue, separators = [",", " ", "\n"], uniqueTokens = new Set()) { | |
const separator = separators.pop(); | |
if (!separator) | |
return uniqueTokens; | |
const tokens = rawValue.split(separator); | |
for (let token of tokens) { | |
let hasOtherSeparator = false; | |
for (let s1 of separators) { | |
if (token.includes(s1)) { | |
hasOtherSeparator = true; | |
break; | |
} | |
} | |
if (hasOtherSeparator) { | |
uniqueTokens = splitByMultipleSeparators(token, separators, uniqueTokens); | |
} else { | |
uniqueTokens.add(token); | |
} | |
} | |
return uniqueTokens; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment