轉載—–JavaScript如何對後台utf8編碼的字串解碼

來源:互聯網
上載者:User

原文

  為了防止xss以及csrf+xss的漏洞,後台統一對字串進行了轉碼。結果如下:
原文: JavaScript進階程式設計
編碼: JavaScript高级程序设计

  前端寫了一段如下代碼:

function u2str(text){// transform text in utf8 format to string
        return unescape(text.replace(/&#/g,'%u').replace(/;/g,''));
}

  對普通的中文沒問題,但是對上面的中英文載入的文本,這個函數就會返回亂碼。

  我們可以使用原生的Javascript代碼來進行轉義。該編碼其實不是utf8,而是unicode編碼。這裡的字元實際上是html實體。

var decodeHtmlEntity =function(str){
  return str.replace(/&#(\d+);/g,function(match, dec){
    return String.fromCharCode(dec);
  });
};

輸入:

var str ='JavaScript高级程序设计';
console.log(decodeHtmlEntity(str));

輸出:

JavaScript進階程式設計

  以下代碼用於將正常的字元轉變為html實體

var encodeHtmlEntity =function(str){
  var buf =[];
  for(var i=str.length-1;i>=0;i--){
    buf.unshift(['&#', str[i].charCodeAt(),';'].join(''));
  }
  return buf.join('');
};

輸入:

var str ='進階程式設計';
console.log(encodeHtmlEntity(str));

輸出:

高级程序设计

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.