Reprinted -- how does JavaScript decode UTF-8 encoded strings in the background?

Source: Internet
Author: User
Tags javascript decode

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:

高级程序设计

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.