The tag means: "The browser may insert a line break here, if it wishes." It the browser does not think a line break necessary nothing happens" - Check the overhauling on ppk.

If you type a looooooooooooooooong word on google talk of Gmail it injects tags from 15 by 15. We know there is a lot of ways to write a solution to do it, some of them looking for a better performance another looking for elegance.

I was wondering how is the best way to insert tags inside a long string, off course, the solution can be used to insert any piece of string inside another.

The first solution I found have a better performance:

function wbr(str, r) {
	r = r || 15;
    var t = str.length, out = "";
   
    for (var i = 0; i < Math.ceil(t/r); i++)
        out = [ out, [str.slice(i*r, i*r+r), i*r+r >= t ? "" : "<wbr>"].join("") ].join("");
   
    return out;
};


The second, is more elegant, but have a worse performance:

function wbr2(str) {
	var wbr = "<wbr>", r = arguments[1] || 15, i = 1, out = "";
	
	str.replace(/(.{1})/g, function(piece) {
		out = [out, piece, i++%r==0 ? wbr : "" ].join("");
	});
	
	return out;
} 


Trying some of the functions above:

// the first solution //alert( wbr("abcdefghij", 5) ); // the second alert( wbr2("abcdefghij", 5) );

Do you have another intresting way to do this injection?
I'm eager to know your ideas!




After a quick chat with John Resig he gave me in amazing 3 minutes another way to do it, check his idea below: (thanks John!)

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

Post a Comment » | Social Bookmarks » | Posted in JavaScript javascript, html, tags

4 Comments

by Brian [ bchan@liferay.com ] on 07/08/2008 01:50
Good jog!
by Igor Mattos [ igor.mattos@hotmail.com ] on 29/05/2008 18:12
Hey braker!
if you don't remember me, i am rafael's (paper xD) brother..
I hope to learn a lot of things here..
Nice blog !
Keep up the good work !

by Nate Cavanaugh [ ncavanaugh@liferay.com ] on 24/05/2008 18:15
Heya Eduardo! Just found your blog from John's blog. Great stuff. I'm looking forward to next month when you join Liferay, it should be an awesome time.

Just thought I'd say hi :)
by Bruno [ b.basto@gmail.com ] on 15/05/2008 22:01
Great job braeker!!
It fits very well in the chat i'm working on.. thanks.
i tested its performance and the the first one seems to be 1000 times faster since it doesn't use regular expressions!!!