Last active
September 23, 2024 06:54
-
-
Save hendriklammers/5231994 to your computer and use it in GitHub Desktop.
Javascript: Split String into size based 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
/** | |
* Split a string into chunks of the given size | |
* @param {String} string is the String to split | |
* @param {Number} size is the size you of the cuts | |
* @return {Array} an Array with the strings | |
*/ | |
function splitString (string, size) { | |
var re = new RegExp('.{1,' + size + '}', 'g'); | |
return string.match(re); | |
} |
Worked like magic.
Thanks
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Really handy. Can I recommend
'[^]{1,' + size + '}' so that newlines are included in the chunks? You could have that as an argument on
splitString` even. Like: