Skip to content

Instantly share code, notes, and snippets.

@hendriklammers
Last active January 6, 2024 15:46
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • 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);
}
@UlisesGascon
Copy link

works perfect! thanks for share it :-)

@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