encodeURIComponent(val);
encodeURIComponent()的作用是把字符串作为URI进行编码。
对字符串进行编码的原因是——如果参数中有特殊字符(空格等)时,避免传参失误。
encodeURIComponent(val);
入参 | 描述 |
---|---|
val | 字符串,含有 URI 组件或其他要编码的文本 |
返回值:
返回的字符串中某些字符被 十六进制 的 转义序列 进行替换。
语法:
encodeURIComponent(str);
Demo:
let url="http://www.baidu.com";
console.log(encodeURIComponent(url));
//返回值是
http%3A%2F%2Fwww.baidu.com
url中的 : / /被替换成 %3A%2F%2F
url携带参数的情况下:
let url="http://www.baidu.com?name=小米&age=18";
console.log(encodeURIComponent(url));
//返回值是
http%3A%2F%2Fwww.baidu.com%3Fname%3D%E5%B0%8F%E7%B1%B3%26age%3D18
: / / 替换成 %3A%2F%2F
? 替换成 %3F
=小米& 替换成 %3D%E5%B0%8F%E7%B1%B3%26
= 替换成 %3D