JS URL编码
1JS URL编码
URL编码是一种将字符串转换为URL兼容格式的过程。URL中含有特殊字符,如问号(?)、井号(#)、空格等,为了避免这些字符影响URL的正确性,需要进行编码。在JavaScript中,可使用encodeURI()和encodeURIComponent()两个函数实现URL编码。

- encodeURI(str)

encodeURI()函数用于对整个URL进行编码,但不包括字母、数字、下划线、减号等基本字符,只对其他字符进行编码。例如:

```
var url = "https://www.baidu.com/s?wd=JavaScript 编码";
var encodedUrl = encodeURI(url);
console.log(encodedUrl); // https://www.baidu.com/s?wd=JavaScript%20编码
```

- encodeURIComponent(str)

encodeURIComponent()函数用于对URL中参数部分进行编码,包括字母、数字、下划线、减号等基本字符,以及一些特殊字符。例如:

```
var url = "https://www.baidu.com/s?wd=JavaScript 编码";
var encodedUrl = "https://www.baidu.com/s?wd=" + encodeURIComponent("JavaScript 编码");
console.log(encodedUrl); // https://www.baidu.com/s?wd=JavaScript%20%E7%BC%96%E7%A0%81
```

需要注意的是,encodeURI()和encodeURIComponent()函数编码的字符集不同。如果需要对整个URL进行编码,应该使用encodeURI()函数。如果需要对URL中的参数进行编码,应该使用encodeURIComponent()函数。
本页由《梦行文档》生成

 

name完成
30