日期:2014-05-16  浏览次数:20434 次

JS 两种转unicode的方式

两种转unicode的方式
http://www.th7.cn/Article/bc/jv/200906/358189.html

JS-&#unicode;编码转换

?程序代码
<script type="text/javascript">
var toHTML = {
??? on: function(str) {
??????? var a = [],
??????? i = 0;
??????? for (; i < str.length;) a[i] = str.charCodeAt(i++);
??????? return "&#" + a.join(";&#") + ";"
??? },
??? un: function(str) {
??????? return str.replace(/&#(x)?([^&]{1,5});?/g,
??????? function(a, b, c) {
??????????? return String.fromCharCode(parseInt(c, b ? 16 : 10))
??????? })
??? }
};
alert(toHTML.on("\"请输\""));
alert(toHTML.un("大幅"));
</script>


JS-unicode编码转换


?程序代码
<script type="text/javascript">
var toUN = {
??? on: function(str) {
??????? var a = [],
??????? i = 0;
??????? for (; i < str.length;) a[i] = ("00" + str.charCodeAt(i++).toString(16)).slice( - 4);
??????? return "\\u" + a.join("\\u")
??? },
??? un: function(str) {
??????? return unescape(str.replace(/\\/g, "%"))
??? }
};
alert(toUN.on("\"请输\""));
alert(toUN.un("\\u0022\\u8BF7\\u8F93\\u0022"));
</script>

?

?

另一种转码方法(只支持#$一种方式,含转去转回)

<script language = "JavaScript">
function unicode(s){
var len=s.length;
var rs="";
for(var i=0;i<len;i++){
var k=s.substring(i,i+1);
rs+="&#"+s.charCodeAt(i)+";";
}
return rs;
}

function runicode(s){
var k=s.split(";");
var r="";
for(var x=0;x<k.length;x++){
var m=k[x].replace(/&#/,"");
r += String.fromCharCode(m);
}
return r;
}
</script>

?