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!
Hi James,
Nice use of regular expressions to remove the computationally heavy bits out of Javascript. My first rule of performant Javascript is to not use Javascript if there’s a built-in method. (However, Safari 4, FF 3.5, and Chrome 2 make this less of a strict rule than it was even a few months ago.)
I am having trouble figuring out why I’d need this in a real app, though. Why not let the browser word-wrap using CSS? In what scenarios have you used this?
— John
@unscriptable, I haven’t really considered any uses for this yet (on the client-side). I clicked a link to another solution yesterday and it dissapointed me; I thought this could be done more gracefully; so, I wrote my own.
‘|\S+?(\s|$)’ do you mean ‘|(\S+)?(\s|$)’ ?
i can not understant the ‘+?’, could you tell me what this for ?
thanks alot 🙂
Thank you for this function. It works great in the browser environment. However, I am trying to use it in Mirth (a java based application that runs javascript) and it keeps putting a brk anywhere there is a space in the string. Is there some variation that is possible to prevent this.
Hey just wanted to let you know I found the issue and created this work around for Mirth:
brk = (brk ? brk :’n’);
width = (width ? width : 75);
cut = (cut ? cut : false);
Thank you for this function it is great.
This is far more elegant than alot of scripts that do the same thing. Only I dont want to word wrap just cut the string on the specified length and append the break “…”.
If I set to false or true this script still cuts it up into lines?
Any idea how to just return the string with specified length with brk appended?