Last active
August 20, 2022 23:13
-
-
Save albannurkollari/c5d80d26ab62af02bee8e9abf57e08db to your computer and use it in GitHub Desktop.
Tokenize a string consequetively and split into chunks
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
const tokenizeStrAndSplitIntoChunks = (strToTokenize = '') => | |
[...strToTokenize].reduce( | |
(acc, letter, i, { length }) => { | |
if (/\w+/.test(letter)) { | |
acc[acc.length - 1] += letter; | |
} else if (i !== length - 1 && acc.at(-1) !== '') { | |
acc.push(''); | |
} | |
return acc; | |
}, | |
[''] | |
); | |
const myStr = `He is a very very good boy, isn't he?`; | |
if (/[A-Za-z!,?._'@]/.test(myStr)) { | |
console.log(tokenizeStrAndSplitIntoChunks(myStr)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation:
.reduce
built-in method for it, with an initial value of one blank string!\w
regex character class.3.1. If it is, than we append that letter to the end of the previous str as seen in line 5.
3.2 If not, **than we also check if the letter is NOT the last in the spreaded string ** and that last added item into the accumulator is not an empy string, because in the case of
,
(comma and blank consequetively), we'd end up adding an empty string without that condition.