Posts Tagged ‘Strings’

“wordwrap” for JavaScript

Posted in 'Code Snippets, JavaScript, PHP' by James on June 26th, 2009

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…

Fastest way to build an HTML string

Posted in 'Code Snippets, JavaScript' by James on May 29th, 2009

You have a massive array of items that needs to be transformed into an HTML list without causing the user any grief. There are a couple common ways of doing this:

Note: I’m not even going to bother covering direct DOM manipulation for every list item because that’d be plain stupid!

#1 – Step-by-step string concat

Not the slowest method that exists but probably the most common:

var arr = ['item 1', 'item 2', 'item 3', ...],
    list = '';
 
for (var i = 0, l = arr.length; i < l; i++) {
    list += '<li>' + arr[i] + '</li>';
}
 
list = '<ul>' + list + '</ul>';

Don’t use this. It’s inefficient, slow and ugly!

#2 – Step-by-step array pushing

var arr = ['item 1', 'item 2', 'item 3', ...],
    list = [];
 
for (var i = 0, l = arr.length; i < l; i++) {
    list[list.length] = '<li>' + arr[i] + '</li>';
}
 
list = '<ul>' + list.join('') + '</ul>';

Slightly faster than string concatenation but still not perfect…

#3 – The holy grail!

var arr = ['item 1', 'item 2', 'item 3', ...];
 
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) – this is by far the fastest method!

Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.

Browser benchmarks

Due to a request and my own curiousity I’ve conducted a quick benchmarking test. Each method was tested with a 130-item array, the length of each item varied so any optimizations on the browser’s part would not be effective. Each method was tested 1000 times; the results below show how long each browser took to complete each method 1000 times:

“String concat” (ms) “Array pushing” (ms) “Native join()” (ms)
Firefox 3 147 148 65
Opera 9 172 125 78
IE 7 500 2297 79
Chrome 2 63 88 72
Safari 4b 146 141 60
Averages 205 559 70

Surprisingly, string concatenation came out much faster than “array pushing” on average. It seems IE7 optimizes for lengthy string operations but doesn’t care much for arrays. Also, Google Chrome performed oddly; the “string concatenation” method was quicker than the “native join()”… I’m not too sure what’s going on there! Anyway, the results were mostly predictable, and, of course, “native join()” came out on top!