汉字转utf-8的js代码
作者:admin 日期:2008-11-22
<script>
function UTF8UrlEncode(input)
{
var output = "";
var currentChar = '';
for(var counter = 0; counter < input.length; counter++)
{
currentChar = input.charCodeAt(counter);
if((48 <= currentChar) && (currentChar <= 57))
output = output + input.charAt(counter);
else if((65 <= currentChar) && (currentChar <= 90))
output = output + input.charAt(counter);
else if((97 <= currentChar) && (currentChar <= 122))
output = output + input.charAt(counter);
else
output = output + UTF8UrlEncodeChar(currentChar);
}
return output;
}
function UTF8UrlEncodeChar(input)
{
if(input <= 0x7F) return "%" + input.toString(16);
var leadByte = 0xFF80; var hexString = ""; var leadByteSpace = 5;
while(input > (Math.pow(2, leadByteSpace + 1) - 1))
{
hexString = "%" + ((input & 0x3F) | 0x80).toString(16) + hexString;
leadByte = (leadByte >> 1);
leadByteSpace--;
input = input >> 6;
}
return ("%" + (input | (leadByte & 0xFF)).toString(16) + hexString).toUpperCase();
}
//下面是测试
document.write("<a href=http://www.google.com/search?q="+UTF8UrlEncode("谷歌")+">go</a>");
</script>