Original
To prevent xss and csrf + xss vulnerabilities, strings are transcoded in the background. The result is as follows:
Original article: JavaScript Advanced Programming
Code: JavaScript & #39640; & #32423; & #31243; & #24207; & #35774; & #35745;
The front end writes the following code:
function u2str(text){// transform text in utf8 format to string
return unescape(text.replace(/&#/g,'%u').replace(/;/g,''));
}
This function is correct for common Chinese characters, but returns garbled characters for the texts loaded in both Chinese and English.
We can use native Javascript code for escape. This encoding is not utf8, But unicode encoding. The characters here are actually html objects.
var decodeHtmlEntity =function(str){
return str.replace(/&#(\d+);/g,function(match, dec){
return String.fromCharCode(dec);
});
};
Input:
var str ='JavaScript高级程序设计';
console.log(decodeHtmlEntity(str));
Output:
JavaScript Advanced Programming
Run the following code to convert normal characters into html objects:
var encodeHtmlEntity =function(str){
var buf =[];
for(var i=str.length-1;i>=0;i--){
buf.unshift(['&#', str[i].charCodeAt(),';'].join(''));
}
return buf.join('');
};
Input:
Var str = 'advanced programming Design ';
Console. log (encodeHtmlEntity (str ));
Output:
高级程序设计