Injecting Word Breaks with JavaScript

Recently Eduardo Lundgren pinged me wondering if I had an alternate solution to injecting wbr tags inside a long word.

The wbr tag tells the browser where a possible line break can be inserted, should the need arise. (Opera has some problems with rendering them correctly, but it can be rectified using some CSS.) By adding wbr tags into words at strategic locations you can allow a content area to resize gracefully while still being readable.

I looked at his simplified solutions for a moment and came up with this solution:

function wbr(str, num) {  
  return str.replace(RegExp("(\\w{" + num + "})(\\w)", "g"), function(all,text,char){ 
    return text + "<wbr>" + char; 
  }); 
}

You would use it like so:

wbr("Hello everyone how are you doing?" + 
  "I'm writing an extravagently long string.", 6);

"Hello everyo<wbr>ne how are you doing? I'm writin<wbr>g an extrav<wbr>agently long string."

Now this is an incredibly simple solution and having breaks like writin<wbr>g are quite undesirable. After I wrote the above I did some more digging and read about various hyphenation algorithms that exist.

Looking in the above article I found a recent JavaScript library which provides a full solution (breaking in appropriate places for multiple languages). Of course, the resulting code checks in at about 80kb (15kb base library + 65kb English word library) so you’ll need to strongly consider if that solution is appropriate for your situation.

Posted: May 24th, 2008


Subscribe for email updates

12 Comments (Show Comments)



Comments are closed.
Comments are automatically turned off two weeks after the original post. If you have a question concerning the content of this post, please feel free to contact me.


Secrets of the JavaScript Ninja

Secrets of the JS Ninja

Secret techniques of top JavaScript programmers. Published by Manning.

John Resig Twitter Updates

@jeresig / Mastodon

Infrequent, short, updates and links.