decodeURI和decodeURIComponent


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/06/26/decodeURI%E5%92%8CdecodeURIComponent/

摘要

本文主要讲述了:

  1. 作用
  2. 实现

正文

作用

将 UTF-8 的转义序列转换为 UTF-16 字符串

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// "中文"
console.log(decodeURIComponent('%E4%B8%AD%E6%96%87'));
</script>
</body>
</html>

实现

注意:仅实现了%xx格式的解析,没有实现不需要编码的字符的解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
function decodeURIComponentPartialImplementation(str) {
// console.log(str);
return new Blob(
[
Uint8Array.from(str.slice(1).split('%'), function (char) {
return Number.parseInt(`0x${char}`, 16);
}),
],
{
type: 'text/plain',
}
).text();
}

const str = '😊';
decodeURIComponentPartialImplementation(encodeURIComponent(str)).then(
(value) => {
console.log(value);
console.log(decodeURIComponent(encodeURIComponent(str)));

// true
console.log(decodeURIComponent(encodeURIComponent(str)) === value);
}
);
</script>
</body>
</html>

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/06/26/decodeURI%E5%92%8CdecodeURIComponent/


本文对你有帮助?请支持我


支付宝
微信