我使用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(/\\/g, '&#92;')

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

其他回答

基于angular的sanitize…(es6模块语法)

// ref: https://github.com/angular/angular.js/blob/v1.3.14/src/ngSanitize/sanitize.js
const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
const NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;

const decodeElem = document.createElement('pre');


/**
 * Decodes html encoded text, so that the actual string may
 * be used.
 * @param value
 * @returns {string} decoded text
 */
export function decode(value) {
  if (!value) return '';
  decodeElem.innerHTML = value.replace(/</g, '&lt;');
  return decodeElem.textContent;
}


/**
 * Encodes all potentially dangerous characters, so that the
 * resulting string can be safely inserted into attribute or
 * element text.
 * @param value
 * @returns {string} encoded text
 */
export function encode(value) {
  if (value === null || value === undefined) return '';
  return String(value).
    replace(/&/g, '&amp;').
    replace(SURROGATE_PAIR_REGEXP, value => {
      var hi = value.charCodeAt(0);
      var low = value.charCodeAt(1);
      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
    }).
    replace(NON_ALPHANUMERIC_REGEXP, value => {
      return '&#' + value.charCodeAt(0) + ';';
    }).
    replace(/</g, '&lt;').
    replace(/>/g, '&gt;');
}

export default {encode,decode};

好的答案。注意,在jQuery 1.4.2中,如果要编码的值是undefined或null,你可能会得到如下错误:

jQuery("<div/>").text(value).html不是一个函数

OR

对象没有方法“html”

解决方案是修改函数来检查实际值:

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

我有一个类似的问题,解决它使用函数encodeURIComponent从JavaScript(文档)

例如,在你的例子中,如果你使用:

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

and

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

你会得到粉笔%20%26%20奶酪。甚至空格也要保留。

在我的情况下,我必须编码一个反斜杠,这段代码完美地工作

encodeURIComponent('name/surname')

我的名字是% 2姓氏

如果你想使用jQuery。我发现了这个:

http://www.jquerysdk.com/api/jQuery.htmlspecialchars

(jquery的一部分。jQuery SDK提供的字符串插件

我认为Prototype的问题在于它扩展了JavaScript中的基本对象,并且与你可能使用过的任何jQuery都不兼容。当然,如果你已经在使用Prototype而不是jQuery,这就不是问题。

编辑:还有这个,这是Prototype的字符串实用工具的jQuery端口:

http://stilldesigning.com/dotstring/

我的pure-JS函数:

/**
 * HTML entities encode
 *
 * @param {string} str Input text
 * @return {string} Filtered text
 */
function htmlencode (str){

  var div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
}

JavaScript HTML实体编码和解码