编码转换(to unicode)

本文提供了多种语言实现字符串到HTML实体编码的示例代码,包括JavaScript、VBS和ColdFusion等,展示了如何将中文字符转换为对应的Unicode编码形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Js版

<script>
     test = "你好abc"
     str = ""
     for( i=0;    i<test.length; i++ )
     {
      temp = test.charCodeAt(i).toString(16);
      str    += "\\u"+ new Array(5-String(temp).length).join("0") +temp;
     }
     document.write (str)
</script>

vbs版

Function Unicode(str1)
     Dim str,temp
     str = ""
     For i=1    to len(str1)
      temp = Hex(AscW(Mid(str1,i,1)))
      If len(temp) < 5 Then    temp = right("0000" & temp, 4)
      str = str & "\u" & temp
     Next
     Unicode = str
End Function

Function htmlentities(str)
     For i = 1 to Len(str)
         char = mid(str, i, 1)
         If Ascw(char) > 128 then
             htmlentities = htmlentities & "&#" & Ascw(char) & ";"
         Else
             htmlentities = htmlentities & char
         End if
     Next
End Function

 

 

coldfusion

function nochaoscode(str)
{
     var new_str = “”;
     for(i=1; i lte len(str);i=i+1){
         if(asc(mid(str,i,1)) lt 128){
             new_str = new_str & mid(str,i,1);
         }else{
             new_str = new_str & “&##” & asc(mid(str,i,1));
         }
     }
     return new_str;
}


附:在php中我们可以用mbstring的mb_convert_encoding函数实现这个正向及反向的转化。 如:

mb_convert_encoding ("你好", "HTML-ENTITIES", "gb2312"); //输出:&#20320;&#22909;

mb_convert_encoding ("&#20320;&#22909;", "gb2312", "HTML-ENTITIES"); //输出:你好

 

如果需要对整个页面转化,则只需要在php文件的头部加上这三行代码:

mb_internal_encoding("gb2312"); // 这里的gb2312是你网站原来的编码

mb_http_output("HTML-ENTITIES");

ob_start('mb_output_handler');


转载自 http://xiaoxinshome.iteye.com/blog/390945

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值