Skip to content

Instantly share code, notes, and snippets.

@KooiInc
Created November 9, 2023 11:41
Show Gist options
  • Save KooiInc/90266066ca30064a8f7b8e93c0356493 to your computer and use it in GitHub Desktop.
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.
/*
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