zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JS文字符串转换unicode编码函数

JS转换编码 函数 字符串 Unicode
2023-06-13 09:14:09 时间
复制代码代码如下:

functionuniencode(text)
{
text=escape(text.toString()).replace(/\+/g,"%2B");
varmatches=text.match(/(%([0-9A-F]{2}))/gi);
if(matches)
{
for(varmatchid=0;matchid<matches.length;matchid++)
{
varcode=matches[matchid].substring(1,3);
if(parseInt(code,16)>=128)
{
text=text.replace(matches[matchid],"%u00"+code);
}
}
}
text=text.replace("%25","%u0025");
returntext;
}

当然服务器端要对编码过的字符串进行第二次转码.把字符串转换成UTF-8编码. 
复制代码代码如下:

functionconvert_int_to_utf8($intval)
{
$intval=intval($intval);
switch($intval)
{
//1byte,7bits
case0:
returnchr(0);
case($intval&0x7F):
returnchr($intval);
//2bytes,11bits
case($intval&0x7FF):
returnchr(0xC0|(($intval>>6)&0x1F)).
chr(0x80|($intval&0x3F));
//3bytes,16bits
case($intval&0xFFFF):
returnchr(0xE0|(($intval>>12)&0x0F)).
chr(0x80|(($intval>>6)&0x3F)).
chr(0x80|($intval&0x3F));
//4bytes,21bits
case($intval&0x1FFFFF):
returnchr(0xF0|($intval>>18)).
chr(0x80|(($intval>>12)&0x3F)).
chr(0x80|(($intval>>6)&0x3F)).
chr(0x80|($intval&0x3F));
}
}

这样中文字符串就可以转换成UTF-8编码.这种方法适合各种服务器环境..