我使用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编码?


当前回答

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

}

var aString = '<script>alert("I hack your site")</script>';
console.log(aString.htmlEncode());
</script>

将输出:&lt;script&gt;alert(&quot;I hack your site&quot;)&lt;/script&gt;

. htmlencode()一旦定义,就可以在所有字符串上访问。

其他回答

Prototype内置了String类。所以如果你正在使用/计划使用Prototype,它会像这样做:

'<div class="article">This is an article</div>'.escapeHTML();
// -> "&lt;div class="article"&gt;This is an article&lt;/div&gt;"

function encodeHTML(str) { return document.createElement(“a”).appendChild( document.createTextNode(str)).parentNode.innerHTML; }; 函数解码HTML(str) { var element = document.createElement(“a”); element.innerHTML = str; 返回元素文本内容; }; var str = “<” var enc = encodeHTML(str); var dec = decodeHTML(enc); console.log(“str: ” + str, “\nenc: ” + enc, “\ndec: ” + dec);

基于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};

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

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

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

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

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

and

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

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

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

encodeURIComponent('name/surname')

我的名字是% 2姓氏