Skip to content

Instantly share code, notes, and snippets.

@hendriklammers
Last active September 23, 2024 06:54
Show Gist options
  • Save hendriklammers/5231994 to your computer and use it in GitHub Desktop.
Save hendriklammers/5231994 to your computer and use it in GitHub Desktop.
Javascript: Split String into size based chunks
/**
* 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);
}
@crazytonyi
Copy link

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:

function splitString (string, size, multiline) {
        var matchAllToken = (multiline == true) ? '[^]' : '.';
	var re = new RegExp(matchAllToken + '{1,' + size + '}', 'g');
	return string.match(re);
}

@blessdarah
Copy link

Worked like magic.
Thanks

@Mmasoud1
Copy link

Mmasoud1 commented Jan 6, 2024

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment