我使用JavaScript从隐藏字段中拉出一个值并在文本框中显示它。隐藏字段中的值被编码。

例如,

<input id='hiddenId' type='hidden' value='chalk &amp; cheese' />

被卷入

<input type='text' value='chalk &amp; cheese' />

通过一些jQuery来获取隐藏字段的值(在这一点上,我失去了编码):

$('#hiddenId').attr('value')

问题是当我读粉笔&cheese从隐藏字段,JavaScript似乎失去了编码。我不希望价值是粉笔和奶酪。我想要字面上的amp;被保留。

是否有JavaScript库或jQuery方法可以对字符串进行html编码?


当前回答

使用这里的一些其他答案,我做了一个版本,在一次传递中替换所有相关字符,而不考虑不同编码字符的数量(只需调用replace()),因此对于较大的字符串将更快。

它不依赖于DOM API存在,也不依赖于其他库。

window.encodeHTML = (function() {
    function escapeRegex(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }
    var encodings = {
        '&'  : '&amp;',
        '"'  : '&quot;',
        '\'' : '&#39;',
        '<'  : '&lt;',
        '>'  : '&gt;',
        '\\' : '&#x2F;'
    };
    function encode(what) { return encodings[what]; };
    var specialChars = new RegExp('[' +
        escapeRegex(Object.keys(encodings).join('')) +
    ']', 'g');

    return function(text) { return text.replace(specialChars, encode); };
})();

运行了一次之后,您现在可以调用

encodeHTML('<>&"\'')

得到&lt;&gt;&& #39;

其他回答

编辑:这个答案是很久以前发布的,htmlDecode函数引入了一个XSS漏洞。它已被修改,将临时元素从div改为textarea,减少XSS的机会。但是现在,我鼓励您像其他回答中建议的那样使用DOMParser API。


我使用这些函数:

function htmlEncode(value){
  // Create a in-memory element, set its inner text (which is automatically encoded)
  // Then grab the encoded contents back out. The element never exists on the DOM.
  return $('<textarea/>').text(value).html();
}

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

基本上,textarea元素是在内存中创建的,但它永远不会追加到文档中。

在htmlEncode函数上,我设置了元素的innerText,并检索编码的innerHTML;在htmlDecode函数上,我设置了元素的innerHTML值,并检索了innerText。

在这里查看一个正在运行的示例。

FWIW,编码没有丢失。编码由标记解析器(浏览器)在页面加载期间使用。读取和解析源代码后,浏览器将DOM加载到内存中,编码就被解析成它所表示的内容。所以当你的JS被执行读取内存中的任何东西时,它得到的字符就是编码所表示的。

在这里,我可能严格按照语义操作,但我希望您理解编码的目的。“失去”这个词听起来像是某件事没有像它应该做的那样运作。

var htmlEnDeCode = (function() {
    var charToEntityRegex,
        entityToCharRegex,
        charToEntity,
        entityToChar;

    function resetCharacterEntities() {
        charToEntity = {};
        entityToChar = {};
        // add the default set
        addCharacterEntities({
            '&amp;'     :   '&',
            '&gt;'      :   '>',
            '&lt;'      :   '<',
            '&quot;'    :   '"',
            '&#39;'     :   "'"
        });
    }

    function addCharacterEntities(newEntities) {
        var charKeys = [],
            entityKeys = [],
            key, echar;
        for (key in newEntities) {
            echar = newEntities[key];
            entityToChar[key] = echar;
            charToEntity[echar] = key;
            charKeys.push(echar);
            entityKeys.push(key);
        }
        charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g');
        entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
    }

    function htmlEncode(value){
        var htmlEncodeReplaceFn = function(match, capture) {
            return charToEntity[capture];
        };

        return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
    }

    function htmlDecode(value) {
        var htmlDecodeReplaceFn = function(match, capture) {
            return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
        };

        return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
    }

    resetCharacterEntities();

    return {
        htmlEncode: htmlEncode,
        htmlDecode: htmlDecode
    };
})();

这是ExtJS的源代码。

我知道这是一个老问题,但我想发布一个可接受的答案的变化,在IE中工作而不删除行:

function multiLineHtmlEncode(value) {
    var lines = value.split(/\r\n|\r|\n/);
    for (var i = 0; i < lines.length; i++) {
        lines[i] = htmlEncode(lines[i]);
    }
    return lines.join('\r\n');
}

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

我在我的域\用户字符串中遇到了一些反斜杠问题。

我把这个加到了安特洛皮克的答案的其他逃脱中

.replace(/\\/g, '&#92;')

我在这里找到了: 如何在JavaScript中逃脱反斜杠?