我使用JavaScript从隐藏字段中拉出一个值并在文本框中显示它。隐藏字段中的值被编码。
例如,
<input id='hiddenId' type='hidden' value='chalk & cheese' />
被卷入
<input type='text' value='chalk & cheese' />
通过一些jQuery来获取隐藏字段的值(在这一点上,我失去了编码):
$('#hiddenId').attr('value')
问题是当我读粉笔&cheese从隐藏字段,JavaScript似乎失去了编码。我不希望价值是粉笔和奶酪。我想要字面上的amp;被保留。
是否有JavaScript库或jQuery方法可以对字符串进行html编码?
没有Jquery更快。你可以对字符串中的每个字符进行编码:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
或者只关注主要角色(&,inebreaks, <, >, "和'),比如:
函数编码(r) {
返回r.replace (/ [\ x26 \ x0A \ < > "] / g函数(r){返回" & # + r.charCodeAt(0) +”;“})
}
测试。value=encode('编码HTML实体!\n\n"安全"转义<脚本id=\'\'> &有用在<pre>标签!');
testing.innerHTML = test.value;
/*************
* \x26是& &号(必须排在第一位),
* \x0A为换行符,
*************/
<textarea id=test rows="9" cols="55"></textarea>
www.WHAK.com < div id = "测试" > < / div >
选择escapeHTML()在prototype.js中做什么
添加这个脚本可以帮助你逃脱html:
String.prototype.escapeHTML = function() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
}
现在你可以在脚本中对字符串调用escapeHTML方法,比如:
var escapedString = "<h1>this is HTML</h1>".escapeHTML();
// gives: "<h1>this is HTML</h1>"
希望它能帮助任何人寻找一个简单的解决方案,而不必包括整个prototype.js
没有Jquery更快。你可以对字符串中的每个字符进行编码:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
或者只关注主要角色(&,inebreaks, <, >, "和'),比如:
函数编码(r) {
返回r.replace (/ [\ x26 \ x0A \ < > "] / g函数(r){返回" & # + r.charCodeAt(0) +”;“})
}
测试。value=encode('编码HTML实体!\n\n"安全"转义<脚本id=\'\'> &有用在<pre>标签!');
testing.innerHTML = test.value;
/*************
* \x26是& &号(必须排在第一位),
* \x0A为换行符,
*************/
<textarea id=test rows="9" cols="55"></textarea>
www.WHAK.com < div id = "测试" > < / div >
基于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, '<');
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, '&').
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, '<').
replace(/>/g, '>');
}
export default {encode,decode};