1.encodeURI()
encodeURI()方法用于转码整个 URL。它的参数是一个字符串,代表整个 URL。它会将元字符和语义字符之外的字符,都进行转义。
console.log(encodeURI('http://www.example.com/name=张三'));
/*http://www.example.com/name=%E5%BC%A0%E4%B8%89*/
2.encodeURIComponent()
encodeURIComponent()方法用于转码 URL 的组成部分,会转码除了语义字符之外的所有字符,即元字符也会被转码。所以,它不能用于转码整个 URL。它接受一个参数,就是 URL 的片段。
console.log(encodeURIComponent('上海'));
//%E4%B8%8A%E6%B5%B7
console.log(encodeURIComponent('http://www.example.com/city=上海'));
//http%3A%2F%2Fwww.example.com%2Fcity%3D%E4%B8%8A%E6%B5%B7
上面代码中,encodeURIComponent()会连 URL 元字符一起转义,所以如果转码整个 URL 就会出错。
3.decodeURI()
decodeURI()方法用于整个 URL 的解码。它是encodeURI()方法的逆运算。它接受一个参数,就是转码后的 URL。
console.log(decodeURI('http://www.example.com/name=%E5%BC%A0%E4%B8%89'));
/*http://www.example.com/name=张三*/
4.decodeURIComponent()
decodeURIComponent()用于URL 片段的解码。它是encodeURIComponent()方法的逆运算。它接受一个参数,就是转码后的 URL 片段。
console.log(decodeURIComponent("%E4%B8%8A%E6%B5%B7"));
//上海
网友评论