js URI编码、解码

编码

几种常用的编码方式:

  1. ASCII编码
  2. Unicode编码
  3. UTF-8编码
  4. GBK编码

URL编码

一、escape、unescape

使用unicode编码,针对字符串,返回字符的unicode编码

escape('中国'); // '%u4E2D%u56FD'

二、encodeURI/encodeURIComponent、decodeURI/decodeURIComponent

使用UTF-8编码, 针对URL

encodeURI/encodeURIComponent编码的区别:后者编码的字符范围更大
前者编码不包含的字符范围:
(1)保留字符:; , / ? : @ & = + $
(2)非转义的字符:A-Z a-z 0-9 - _ . ! ~ * ' ( )
(3)#
后者编码不包含的字符范围:
A-Z a-z 0-9 - _ . ! ~ * ' ( )

一般需要编码整个字符串:使用encodeURI; 编码查询参数、hash、pathname等使用encodeURIComponent

encodeURI("http://www.cnblogs.com/season-huang/some other thing"); // "http://www.cnblogs.com/season-huang/some%20other%20thing";


const param = "http://www.cnblogs.com/season-huang/"; 
param = encodeURIComponent(param);
const url = "http://www.cnblogs.com?next=" + param;
console.log(url) // "http://www.cnblogs.com?next=http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2F"

三、URLSearchParams

针对querystring
// 包含空格和标点符号的参数的示例
let url = new URL('https://google.com/search');

url.searchParams.set('q', 'test me!'); // 添加带有一个空格和一个 ! 的参数

alert(url); // https://google.com/search?q=test+me%21

url.searchParams.set('tbs', 'qdr:y'); // 添加带有一个冒号 : 的参数

// 参数会被自动编码
alert(url); // https://google.com/search?q=test+me%21&tbs=qdr%3Ay

URLSearchParams和encode的编码差异
遵循的URL规范不同,导致某些特殊情况下编码结果不同
例如对ipv6地址的编码

你可能感兴趣的:(javascript编码url)