Fastest html escape

// http://jsperf.com/htmlescape-vs-goog-string-htmlescape
// Если вам нужна самая быстрая функция htmlEspcae, то:

// (1) Просто и быстро
var htmlEscape = (function (){
    var _rhtml = /[&<>\"]/g,
        _map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quote;' },
        _replace = function (c){ return _map[c]; }
    ;

    return function(str) {
        if( typeof str === "string" ){
                if( _rhtml.test(str) ){
                        return str.replace(_rhtml, _replace);
                }
        }
        return str;
    }
})();


// (2) goog.string.htmlEscape -- быстро и очень быстро в Chrome/Node/V8
// http://closure-library.googlecode.com/svn/docs/closure_goog_string_string.js.html
var googStringHtmlEscape = (function (){
    var _ramp = /&/g,
        _rlt = /,
        _rgt = />/g,
        _rquote = /\"/g,
        _rhtml = /[&<>\"]/
   ;

    return function (str){
        // quick test helps in the case when there are no chars to replace, in
        // worst case this makes barely a difference to the time taken
        if( typeof str !== 'string' || !_rhtml.test(str) ) return str;

        // str.indexOf is faster than regex.test in this case
        if( str.indexOf('&') != -1 )  str = str.replace(_ramp, '&amp;');
        if( str.indexOf('<') != -1 )  str = str.replace(_rlt, '&lt;');
        if( str.indexOf('>') != -1 )  str = str.replace(_rgt, '&gt;');
        if( str.indexOf('"') != -1 )  str = str.replace(_rquote, '&quote;');

        return str;
    }
})();​

Комментариев нет:

Отправить комментарий