定义和用法
unescape() 函数可对通过 escape() 编码的字符串进行解码。
语法
参数 | 描述 |
---|---|
string | 必需。要解码或反转义的字符串。 |
返回值
string 被解码后的一个副本。
说明
该函数的工作原理是这样的:通过找到形式为 %xx 和 %uxxxx 的字符序列(x 表示十六进制的数字),用 Unicode 字符 \u00xx 和 \uxxxx 替换这样的字符序列进行解码。
代码实现
static String unescape(String src) {
StringBuffer tmp = new StringBuffer();
try {
int lastPos = 0, pos = 0;
int ch;
while (lastPos < src.length) {
pos = src.indexOf("%", lastPos);
if (pos == lastPos) {
if (src.substring(pos + 1, pos + 2) == 'u') {
ch = int.parse(src.substring(pos + 2, pos + 6), radix: 16);
tmp.write(String.fromCharCode(ch));
lastPos = pos + 6;
} else {
ch = int.parse(src.substring(pos + 1, pos + 3), radix: 16);
tmp.write(String.fromCharCode(ch));
lastPos = pos + 3;
}
} else {
if (pos == -1) {
tmp.write(src.substring(lastPos));
lastPos = src.length;
} else {
tmp.write(src.substring(lastPos, pos));
lastPos = pos;
}
}
}
} catch (e) {
} finally {
return tmp.toString();
}
}
#实例
在本例中,我们使用 unescape() 对编码字符串解码:
var test1 = "Hello%20World%21" ;
test1 = unescape(test1);
print(test1);
输出:
Hello World!