html truncate by javascript

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

var Stack = function () {
    this.items = [];
};

Stack.prototype = {
    size: function () {
        return this.items.length;
    },

    push: function (key) {
        this.items.push(key);
    },

    pop: function () {
        return this.items.pop();
    },
   
    /**
     * dump all close tags and append to truncated content while reaching upperbound
     */
    dumpCloseTag: function () {
        var html = '',
            i, len, tag;

        for(i = 0, len = this.size(); i < len; ++i) {
           tag = this.pop();
           html += '</' + tag.tag + '>';
        }
       
        return html;
    }
};

var stack = new Stack();


/**
 * HTML-Truncate Utility
 * This utility truncates html text and keep tag safe(close properly)
 */
var truncate = function (string, maxLength, options) {
    var content = '',       // traced text
        total = 0,          // record how many characters we traced so far
        matches = true,
        result, index, tag, tail;

    while(matches) {
        matches = /<\/?\w+(\s+\w+="[^"]*")*>/g.exec(string);
        if ( ! matches) { break; }
        result = matches[0];
        index = matches.index;

        // overceed, dump everything to clear stack
        if (total + index > maxLength) {
            content += string.substring(0, maxLength - total);
            content += stack.dumpCloseTag();
           
            break;
        } else {
            total += index;
            content += string.substring(0, index);
        }

        if (-1 === result.indexOf('</')) {
           tail = result.indexOf(' ');
           tail = (-1 === tail) ? result.indexOf('>
') : tail;
            stack.push({
                tag: result.substring(1, tail),
                html: result
            });
        } else {
            stack.pop();
        }

        content += result;

        string = string.substring(index + result.length);
    }

    return content;
}
<script>
Benchmark.prototype.setup = function() {
    var src = '<b class="yui3-highlight">Zooey</b> Deschanel embodies quirky cute and she is quickly becoming America\'s sweetheart. <b class="yui3-highlight">Here</b> are some of the "New Girl" star\'s best looks and information on w<b class="yui3-highlight">here</b> you can buy them';
};
</script>

Preparation code output

var Stack = function () { this.items = []; }; Stack.prototype = { size: function () { return this.items.length; }, push: function (key) { this.items.push(key); }, pop: function () { return this.items.pop(); }, /** * dump all close tags and append to truncated content while reaching upperbound */ dumpCloseTag: function () { var html = '', i, len, tag; for(i = 0, len = this.size(); i < len; ++i) { tag = this.pop(); html += ''; } return html; } }; var stack = new Stack(); /** * HTML-Truncate Utility * This utility truncates html text and keep tag safe(close properly) */ var truncate = function (string, maxLength, options) { var content = '', // traced text total = 0, // record how many characters we traced so far matches = true, result, index, tag, tail; while(matches) { matches = /<\/?\w+(\s+\w+="[^"]*")*>/g.exec(string); if ( ! matches) { break; } result = matches[0]; index = matches.index; // overceed, dump everything to clear stack if (total + index > maxLength) { content += string.substring(0, maxLength - total); content += stack.dumpCloseTag(); break; } else { total += index; content += string.substring(0, index); } if (-1 === result.indexOf('') : tail; stack.push({ tag: result.substring(1, tail), html: result }); } else { stack.pop(); } content += result; string = string.substring(index + result.length); } return content; }

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
html truncate
// customized html truncate
truncate(src, 10);
pending…
text truncate
// native substring
src.substring(0, 10)
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment