Created
November 9, 2023 11:41
-
-
Save KooiInc/90266066ca30064a8f7b8e93c0356493 to your computer and use it in GitHub Desktop.
Split a string into words with or without single spaces, where multiple subsequent spaces are considered words.
This file contains 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
/* | |
Split a string into words with or without single spaces, | |
where multiple subsequent spaces are considered words. | |
*/ | |
function parseWords(txt, includeSingleSpaces = false) { | |
let result = [txt[0]]; | |
txt = txt.slice(1).split(''); | |
while (txt.length) { | |
const last = result[result.length - 1].at(-1); | |
if (txt[0] === ` ` && last === ` ` || txt[0] !== ` ` && last !== ` `) { | |
result[result.length - 1] += txt.shift(); | |
continue; | |
} | |
if (last !== ` ` && txt[0] === ` ` || last === ` ` && txt[0] !== ` `) { | |
result.push(txt.shift()); | |
continue; | |
} | |
result[result.length - 1] += txt.shift(); | |
result.push(txt.shift()); | |
} | |
return includeSingleSpaces ? result : result.filter(v => v !== ` `); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment