js-中文編碼轉utf8


 utf8(str){//中文編碼轉為utf8
         var UTFTranslate = {
         Change:function(pValue){
         return pValue.replace(/[^\u0000-\u00FF]/g,function($0){return escape($0).replace(/(%u)(\w{4})/gi,"&#x$2;")});
         },
         ReChange:function(pValue){
         return unescape(pValue.replace(/&#x/g,'%u').replace(/\\u/g,'%u').replace(/;/g,''));
         }
         };
         return UTFTranslate.Change(str); // "中文sdfsf"
      },

使用時直接調用傳入要轉為utf編碼的字符串

let str = 'http://test/中文下載路徑需要轉為utf8的文件名'

let url = this.utf8(str)

 

擴展:

//UTF字符轉換
var UTFTranslate = {
Change:function(pValue){
return pValue.replace(/[^\u0000-\u00FF]/g,function($0){return escape($0).replace(/(%u)(\w{4})/gi,"&#x$2;")});
},
ReChange:function(pValue){
return unescape(pValue.replace(/&#x/g,'%u').replace(/\\u/g,'%u').replace(/;/g,''));
}
};
例如:
UTFTranslate.ReChange('中文sdfdf'); //"中文sdfdf"
UTFTranslate.Change('中文sdfsf'); // "中文sdfsf"
//Asc轉換
var AscTranslate = {
Change: function(pAscString, pBoxId){
/* 轉ASCII */
box = document.getElementById(pBoxId);
box.innerHTML = '';
for(i = 0; i < pAscString.length; i++)
{
var asc = pAscString.charCodeAt(i);
var str = String.fromCharCode(asc);
box.innerHTML += str + ':' + asc + '<br/>';
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM