欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java实现JS中的escape和UNescape代码分享

程序员文章站 2024-02-29 15:56:40
众所周知,javascript中escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。下面,我们就来看看 java语言中类似javascript...

众所周知,javascript中escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。下面,我们就来看看 java语言中类似javascript中的escape() 和unescape() 转码方法,具体代码如下:

public class escapeunescape {
	public static string escape(string src) {
		int i;
		char j;
		stringbuffer tmp = new stringbuffer();
		tmp.ensurecapacity(src.length() * 6);
		for (i = 0; i < src.length(); i++) {
			j = src.charat(i);
			if (character.isdigit(j) || character.islowercase(j)
					|| character.isuppercase(j))
				tmp.append(j);
			else if (j < 256) {
				tmp.append("%");
				if (j < 16)
					tmp.append("0");
				tmp.append(integer.tostring(j, 16));
			} else {
				tmp.append("%u");
				tmp.append(integer.tostring(j, 16));
			}
		}
		return tmp.tostring();
	}
	public static string unescape(string src) {
		stringbuffer tmp = new stringbuffer();
		tmp.ensurecapacity(src.length());
		int lastpos = 0, pos = 0;
		char ch;
		while (lastpos < src.length()) {
			pos = src.indexof("%", lastpos);
			if (pos == lastpos) {
				if (src.charat(pos + 1) == 'u') {
					ch = (char) integer.parseint(src
							.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastpos = pos + 6;
				} else {
					ch = (char) integer.parseint(src
							.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastpos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastpos));
					lastpos = src.length();
				} else {
					tmp.append(src.substring(lastpos, pos));
					lastpos = pos;
				}
			}
		}
		return tmp.tostring();
	}
	/** 
	 * @disc 对字符串重新编码 
	 * @param src 
	 * @return  
	 */
	public static string isotogb(string src) {
		string strret = null;
		try {
			strret = new string(src.getbytes("iso_8859_1"), "gb2312");
		} catch (exception e) {

		}
		return strret;
	}

	/** 
	 * @disc 对字符串重新编码 
	 * @param src 
	 * @return  
	 */
	public static string isotoutf(string src) {
		string strret = null;
		try {
			strret = new string(src.getbytes("iso_8859_1"), "utf-8");
		} catch (exception e) {

		}
		return strret;
	}
	public static void main(string[] args) {
		string tmp = "中文";
		system.out.println("testing escape : " + tmp);
		tmp = escape(tmp);
		system.out.println(tmp);
		system.out.println("testing unescape :" + tmp);
		system.out.println(unescape("%u6211%u4eec"));
		system.out.println(isotoutf(tmp));
	}
}

输出结果为:

testing escape : 中文
%u4e2d%u6587
testing unescape :%u4e2d%u6587
我们
%u4e2d%u6587

总结

以上就是本文对于java实现js中的escape和unescape代码分享的全部内容,希望对大家有所帮助。

感谢大家对本站的支持!