保留字符必须通过 HTML 转义:我们可以使用字符转义来仅使用 ASCII 字符来表示 HTML、XHTML 或 XML 中的任何 Unicode 字符 [Ex: & - U+00026]。数字字符引用[例如: & 符号 (&) - &
] &命名字符引用[Ex: &
] 是character escape used in markup
.
Original Character XML entity replacement XML numeric replacement
< < <
> > >
" " "
& & &
' ' '
为了在网页中将 HTML 标签显示为正常形式,我们使用<pre>
,<code>
标签,或者我们可以转义它们。通过替换字符串中出现的任何"&"
字符以及字符串"&"
中出现的任何字符来转义">"
字符串">"
。前任:stackoverflow post
function escapeCharEntities() {
var map = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'"
};
return map;
}
var mapkeys = '', mapvalues = '';
var html = {
encodeRex : function () {
return new RegExp(mapkeys, 'g'); // "[&<>"']"
},
decodeRex : function () {
return new RegExp(mapvalues, 'g'); // "(&|<|>|"|')"
},
encodeMap : JSON.parse( JSON.stringify( escapeCharEntities () ) ), // json = {&: "&", <: "<", >: ">", ": """, ': "'"}
decodeMap : JSON.parse( JSON.stringify( swapJsonKeyValues( escapeCharEntities () ) ) ),
encode : function ( str ) {
var encodeRexs = html.encodeRex();
console.log('Encode Rex: ', encodeRexs); // /[&<>"']/gm
return str.replace(encodeRexs, function(m) { console.log('Encode M: ', m); return html.encodeMap[m]; }); // m = < " > SpecialChars
},
decode : function ( str ) {
var decodeRexs = html.decodeRex();
console.log('Decode Rex: ', decodeRexs); // /(&|<|>|"|')/g
return str.replace(decodeRexs, function(m) { console.log('Decode M: ', m); return html.decodeMap[m]; }); // m = < " >
}
};
function swapJsonKeyValues ( json ) {
var count = Object.keys( json ).length;
var obj = {};
var keys = '[', val = '(', keysCount = 1;
for(var key in json) {
if ( json.hasOwnProperty( key ) ) {
obj[ json[ key ] ] = key;
keys += key;
if( keysCount < count ) {
val += json[ key ]+'|';
} else {
val += json[ key ];
}
keysCount++;
}
}
keys += ']'; val += ')';
console.log( keys, ' == ', val);
mapkeys = keys;
mapvalues = val;
return obj;
}
console.log('Encode: ', html.encode('<input type="password" name="password" value=""/>') );
console.log('Decode: ', html.decode(html.encode('<input type="password" name="password" value=""/>')) );
O/P:
Encode: <input type="password" name="password" value=""/>
Decode: <input type="password" name="password" value=""/>