用js替换字符串的最快方法?

时间:2012-09-24 09:16:39

标签: javascript jquery html-encode

当我向服务器提交/ POST数据时,我需要 HTMLencode 其字符(相关的),因为通过设置validationRequest = false禁用输入检查好的做法。

所有解决方案最终替换字符串中的字符:

这就是我写的。

function htmlEncode(str) {
    str = str.replace(/\&/g, "&");
    str = str.replace(/\</g, "&lt;");
    str = str.replace(/\>/g, "&gt;");
    str = str.replace(/ /g, "&nbsp;");
    return str;
}

但显然正则表达式可以用更快的东西取代(不要误解我 - 我喜欢正则表达式)。

此外,使用索引+子字符串似乎很浪费。

最快的方法是什么?

3 个答案:

答案 0 :(得分:11)

function htmlEncode(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

jsperf tests show如果您使用的是最近的浏览器版本,这种方法速度很快,可能是最快的选择

也喜欢这样的方式

function htmlEncode(value){
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

答案 1 :(得分:0)

如果您只是编码HTML实体,可以尝试:

function htmlEncode(str) {
    var d = document.createElement('b');
    d.innerText = str;
    return d.innerHTML;
}

这种方式不是最快的。此测试表明regExp更快:http://jsperf.com/encodehtml

但是,您消耗的HTML越多,差异就越小。

innerText方法似乎更可靠,因为它将利用实体的本机浏览器转换表。使用RegExp,您总是有可能错过某些内容,因为使用RegExp消费HTML并不总是最佳的previous answers indicate

答案 2 :(得分:0)

function htmlEncode(value){
    if (value) {
        return jQuery('<div />').text(value).html();
    } else {
        return '';
    }
}

function htmlDecode(value) {
    if (value) {
        return $('<div />').html(value).text();
    } else {
        return '';
    }
}