Skip to content

Instantly share code, notes, and snippets.

@0xD34D
Created January 15, 2015 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xD34D/f60140415acb8d9af85e to your computer and use it in GitHub Desktop.
Save 0xD34D/f60140415acb8d9af85e to your computer and use it in GitHub Desktop.
function wordwrap( str, width, brk, cut ) {
brk = brk || '\n';
width = width || 75;
cut = cut || false;
if (!str) { return str; }
var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
matches = str.match( new RegExp(regex, 'g') );
for (i = 0; i < matches.length; i++) {
matches[i] = matches[i].trim();
}
return matches.join( brk );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment