js实现php函数urlencode
本文介绍了php函数urlencode的js实现方法并比较js和php各编码函数的区别。
通常form表单的enctype类型为application/x-www-form-urlencoded, 当表单提交后,提交的数据自动被编码,规则为" 除了-_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数,空格则编码为加号(+)。", php的urlencode函数与其功能相同。
js编码方法:escape, encodeURI, encodeURIComponent。
escape可以对大多数符号进行编码,但是对unicode字符无效。
php编码方法:urlencode, rawurlencode, htmlentities。
urlencode和rawurlencode唯一的区别是对空格的编码方式不同,rawurlencode遵循RFC 1738编码将空格转换为%20。
如何用js实现php的urlencode功能,网上流传着一段js和vbscript混写的代码,通用性不好,经测试与urlencode相同。
function URLEncode (clearString) {
2 var output = '';
3 var x = 0;
4 clearString = clearString.toString();
5 var regex = /(^[a-zA-Z0-9-_.]*)/;
6 while (x < clearString.length) {
7 var match = regex.exec(clearString.substr(x));
8 if (match != null && match.length > 1 && match[1] != '') {
9 output += match[1];
10 x += match[1].length;
11 } else {
12 if (clearString.substr(x, 1) == ' ') {
13 //原文在此用clearString[x] == ' ' 做判断, 但ie不支持把字符串当作数组来访问,
14 //修改后两种浏览器都可兼容
15 output += '+';
16 }
17 else {
18 var charCode = clearString.charCodeAt(x);
19 var hexVal = charCode.toString(16);
20 output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
21 }
22 x++;
23 }
24 }
25 return output;
26 }