美文网首页
js url encode decode

js url encode decode

作者: xueyueshuai | 来源:发表于2020-03-20 12:34 被阅读0次

js encodeURI 和 encodeURIComponent 的区别

一、共同点

  1. 把字符串作为 URI 进行编码

  2. 方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。

二、区别

1.encodeURI(URIstring):

对在 URI 中具有特殊含义的 ASCII 标点符号,‘不会’进行转义的:;/?:@&=+$,#

2.encodeURIComponent(URIstring)

对在 URI 中具有特殊含义的 ASCII 标点符号,‘也会’进行转义的:;/?:@&=+$,#

例如
let url = 'http://www.baidu.com?a=1&c=2#abc123 4 -.!~*';
console.log(url);
// http://www.baidu.com?a=1&c=2#abc123 4 -
.!~*

console.log(encodeURI(url));
// http://www.baidu.com?a=1&c=2#abc123%204%20-_.!~*

console.log(encodeURIComponent(url));
//http%3A%2F%2Fwww.baidu.com%3Fa%3D1%26c%3D2%23abc123%204%20-_.!~*

大多数使用 encodeURIComponent


一:Js的Url中传递中文参数乱码问题,重点:encodeURI编码,decodeURI解码:

1.传参页面
Javascript代码:

  1. 接收参数页面:test02.html

二:如何获取Url“?”后,“=”的参数值:

A.首先用window.location.href获取到全部url值。
B.用split截取“?”后的全部
C.split(“?”)后面的[1]内数字,默认从0开始计算

三:Js中escape,unescape,encodeURI,encodeURIComponent区别:

1.传递参数时候使用,encodeURIComponent否则url中很容易被”#”,”?”,”&”等敏感符号隔断。
2.url跳转时候使用,编码用encodeURI,解码用decodeURI。
3.escape() 只是为0-255以外 ASCII字符 做转换工作,转换成的 %u**** 这样的码,如果要用更多的字符如 UTF-8字符库 就一定要用 encodeURIComponent() 或 encodeURI() 转换才可以成 %nn%nn 这的码才可以,其它情况下escape,encodeURI,encodeURIComponent编码结果相同,所以为了全球的统一化进程,在用 encodeURIComponent() 或 encodeURI() 代替 escape() 使用吧!

相关文章

网友评论

      本文标题:js url encode decode

      本文链接:https://www.haomeiwen.com/subject/ftcjyhtx.html