用JavaScript实现PHP的urlencode与urldecode函数

么么茶技术网录 2015-08-12

很多朋友说JavaScript的decodeURI函数也可以实现,但有bug所有呢,下面看下下面的函数,经过测试使用暂时没什么问题,我在之前的文章说过,这个和php的urldecode函数根本不是一回事。下面是我根据高人的代码改写的JavaScript版的urldecode函数,参考的链接在开头提到的文章中有,就不一一列举了。和之前的urlencode函数一样,只实现了utf-8版的。

1、urlencode

使用方法: urlencode(str);

function urlencode(clearString) 
{
	var output = '';
	var x = 0;
	
	clearString = utf16to8(clearString.toString());
	var regex = /(^[a-zA-Z0-9-_.]*)/;

	while (x < clearString.length) 
	{
		var match = regex.exec(clearString.substr(x));
		if (match != null && match.length > 1 && match[1] != '') 
		{
			output += match[1];
			x += match[1].length;
		} 
		else 
		{
			if (clearString[x] == ' ')
				output += '+';
			else 
			{
				var charCode = clearString.charCodeAt(x);
				var hexVal = charCode.toString(16);
				output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
			}
			x++;
		}
	}

	function utf16to8(str) 
	{
		var out, i, len, c;

		out = "";
		len = str.length;
		for(i = 0; i < len; i++) 
		{
			c = str.charCodeAt(i);
			if ((c >= 0x0001) && (c <= 0x007F)) 
			{
				out += str.charAt(i);
			} 
			else if (c > 0x07FF) 
			{
				out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
				out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
				out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
			} 
			else 
			{
				out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
				out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
			}
		}
		return out;
	}

	return output;
}

2、urldecode

使用方法:urldecode(url);

function urldecode(encodedString)
{
	var output = encodedString;
	var binVal, thisString;
	var myregexp = /(%[^%]{2})/;
	function utf8to16(str)
	{
		var out, i, len, c;
		var char2, char3;

		out = "";
		len = str.length;
		i = 0;
		while(i < len) 
		{
			c = str.charCodeAt(i++);
			switch(c >> 4)
			{ 
				case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
				out += str.charAt(i-1);
				break;
				case 12: case 13:
				char2 = str.charCodeAt(i++);
				out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
				break;
				case 14:
				char2 = str.charCodeAt(i++);
				char3 = str.charCodeAt(i++);
				out += String.fromCharCode(((c & 0x0F) << 12) |
						((char2 & 0x3F) << 6) |
						((char3 & 0x3F) << 0));
				break;
			}
		}
		return out;
	}
	while((match = myregexp.exec(output)) != null
				&& match.length > 1
				&& match[1] != '')
	{
		binVal = parseInt(match[1].substr(1),16);
		thisString = String.fromCharCode(binVal);
		output = output.replace(match[1], thisString);
	}
	
	//output = utf8to16(output);
	output = output.replace(/\\+/g, " ");
	output = utf8to16(output);
	return output;
}

当服务器端通过php的urlencode转码的就可以使用js的urldecode进行解析即可。

相关推荐