This function emulates PHP’s wordwrap. It takes four arguments:

  • The string to be wrapped.
  • The column width (a number, default: 75)
  • The character(s) to be inserted at every break. (default: ‘n’)
  • The cut: a Boolean value (false by default). See PHP docs for more info.

The code

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|$)');
 
    return str.match( RegExp(regex, 'g') ).join( brk );
 
}

Usage

wordwrap('The quick brown fox jumped over the lazy dog.', 20, '<br/>n');
The quick brown fox <br/>
jumped over the lazy <br/>
dog.

I know there are other solutions out there; the ones I saw seemed a bit slow though, not to mention unnecessarily complicated/bloated…

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!