Các ký tự dành riêng phải được thoát bằng HTML. Chúng ta có thể sử dụng ký tự thoát để thể hiện bất kỳ ký tự Unicode nào [Ví dụ. & - U+00026] trong HTML, XHTML hoặc XML chỉ sử dụng các ký tự ASCII. Tham chiếu ký tự số [Ví dụ. dấu và (&) - & ] & Tham chiếu ký tự được đặt tên [Ví dụ. & ] là các loại của character escape used in markup
Ký tự gốc Thay thế đối tượng XML Thay thế số XML < > > " < & & & ' ' '
Để hiển thị Thẻ HTML dưới dạng bình thường trong trang web, chúng tôi sử dụng , tags or we can escape them. Escaping the string by replacing with any occurrence of the "&" character by the string "&" and any occurrences of the ">" character by the string ">" . Ex: 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('') );
console.log('Decode: ', html.decode(html.encode('')) );
O/P:
Encode: <input type="password" name="password" value=""/>
Decode:
|