Saturday, March 24, 2007

Add zero-width spaces every 10 characters

For dynamic pages sometimes you can't say in advance what exact content will be, and therefor you have no control of actual content, for example words can be very long, and not wrappable by browser. For this purposes I use special zero-width space (x200B) which exists in HTML specs. I wrote a function which you call on strings whenever you need it: yourStr.HTMLwrap()
Here it is:
/** Add zero-width spaces every 10 characters */
String.prototype.HTMLwrap = function() {
    var i = 0;
    var a = '';
    var len = this.length;
    while(len > i*10+10) {
        a += this.substr(i*10, 10) + '\u200B'
        i++;
    }
    return a + (i>0?this.substring(i*10, this.length):this);
}