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

Roy*_*mir 7 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

这样做的最快方法是什么?

Sen*_*der 13

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

jsperf测试表明,如果你是最近的浏览器版本,这种方法很快,可能是最快的选择

另外一种方式也喜欢这样

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

function htmlDecode(value){
  return $('<div/>').html(value).text();
}
Run Code Online (Sandbox Code Playgroud)