1. 程式人生 > 實用技巧 >js-中文編碼轉utf8

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/>'; }