首頁  >  文章  >  web前端  >  將字串轉換成gb2312或utf-8編碼的參數(js版)_javascript技巧

將字串轉換成gb2312或utf-8編碼的參數(js版)_javascript技巧

WBOY
WBOY原創
2016-05-16 17:37:351272瀏覽

在很多時候,當我們直接在url中傳遞中文參數時,讀到的中文都是亂碼,那我們該怎麼將這些參數轉換呢?

下面我們來介紹一下方法
1、我們新建一個UrlEncode.js 然後將下面的代碼拷貝進去

複製代碼 程式碼如下:

//JS版的Server.UrlEncode編碼函數
String.prototype.UrlEncodeGB2312 = function () {
var str = this var str = this
str = str.replace(/./g, function (sHex) {
window.EnCodeStr = "";
window.sHex = sHex;
window.execScript('window.EnCodeStr (Asc(window.sHex))', "vbscript");
return window.EnCodeStr.replace(/../g, "%{blogcontent}amp;");
});
return str;
}
String.prototype.UrlEncode = function () {
var s = escape(this);
var sa = s.split("%");
var
var retV = "", retE = "";
if (sa[0] != "") {
retV = sa[0];
}
for (var i = 1; i if (sa[i].substring(0, 1) == "u") {
retV = Hex2Utf8(Str2Hex(sa[i].substring(1, 5 )));
if (sa[i].length > 4)
retV = sa[i].substring(5);
}
else retV = "%" sa[i] ;
}
return retV;
}
function Str2Hex(s) {
var c = "";
var n;
var ss = "0123456789DEF"; 🎜>var digS = "";
for (var i = 0; i c = s.charAt(i);
n = ss.indexOf(c) ;
digS = Dec2Dig(eval(n));
}
return digS;
}
function Dec2Dig(n1) {
var s = "";
var
var n2 = 0;
for (var i = 0; i n2 = Math.pow(2, 3 – i);
if (n1 >= n2) {
s = '1';
n1 = n1 – n2;
}
else
s = '0';
}
return s;
}
function Dig2Dec(s) {
var retV = 0;
if (s.length == 4) {
for (var i = 0; i retV = eval (s.charAt(i)) * Math.pow(2, 3 – i);
}
return retV;
}
return -1;
}
function Hex2Utf88 (s) {
var retS = "";
var tempS = "";
var ss = "";
if (s.length == 16) {
tempS = " 1110" s.substring(0, 4);
tempS = "10" s.substring(4, 10);
tempS = "10" s.substring(10, 16);
var sss = "0123456789ABCDEF";
for (var i = 0; i retS = "%";
ss = tempS.substring(i * 8, (eval(i) 1 ) * 8);
retS = sss.charAt(Dig2Dec(ss.substring(0, 4)));
retS = sss.charAt(Dig2Dec(ss.substring(4, 8)));
}
return retS;
}
return "";
}
2、使用方法,當然就是我們的((字串.UrlEncode() )可以將字串轉換為utf-8編碼的url參數((字串.UrlEncodeGB2312() )就可把字串轉換成gb2312編碼的參數,很好吧,O(∩_∩)O哈哈~
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn