hi,欢迎访问本站!
当前位置: 首页Web前端正文

js中url编码的介绍

墨初 Web前端 202阅读

在js脚本中可以使用encodeURI()方法和encodeURIComponent()来对URL进行编码,而解码时可以使用decodeURI()方法和decodeURIComponent()方法。下面博文就给这几个js中的方法详细的说一下。

关于URL中的合法字符

在说url编码之前先说一下在浏览器地址中不会被转义的字符,下面有两种。

1、url元字符

分号(;),逗号(’,’),斜杠(/),问号(?),冒号(:),at(@),&,等号(=),加号(+),美元符号($),井号(#)

2、语义字符

a-z,A-Z,0-9,连词号(-),下划线(_),点(.),感叹号(!),波浪线(~),星号(*),单引号(),圆括号(()`)

js中url编码解码的方法

1、js中encodeURI()方法

encodeURI():将元字符和语义字符之外的字符都进行转义,一般用于知道该URL只用于完整的URL时使用

例:

console.log(encodeURI('https://www.73so.com/post/这是文章.html'));
// https://www.73so.com/post/%E8%BF%99%E6%98%AF%E6%96%87%E7%AB%A0.html

2、js中decodeURI()方法

与Js中encodeURI()方法相对应的解码方法就是decodeURI()。

例:

console.log(decodeURI('https://www.73so.com/post/%E8%BF%99%E6%98%AF%E6%96%87%E7%AB%A0.html'));
// https://www.73so.com/post/这是文章.html

3、js中encodeURIComponent()方法

encodeURIComponent()方法,将除了语义字符之外的字符进行转义,包括元字符,因此,它的参数通常是URL的路径或参数值,而不是整个URL。

例:

console.log(encodeURIComponent('post/这是文章.html?page=55'));
// post%2F%E8%BF%99%E6%98%AF%E6%96%87%E7%AB%A0.html%3Fpage%3D55

4、js中decodeURIComponent()方法

js中的decodeURIComponent()可以还原使用encodeURIComponent()方法加密的url。

例:

console.log(decodeURIComponent('post%2F%E8%BF%99%E6%98%AF%E6%96%87%E7%AB%A0.html%3Fpage%3D55'));
//post/这是文章.html?page=55

以上就是js脚本中对url进行编码以及解码的方法,各位可以根据自身的需求进行选择。

声明:无特别说明,转载请标明本文来源!
相关推荐