【JavaScript编程】encodeURI和encodeURIComponent的区别

一、encodeURI

encodeURI函数主要用于编码整个URL。当URL中包含非ASCII字符、空格或其他在URL中有特殊意义的字符时,可以使用encodeURI进行编码。下面是一个使用encodeURI的例子:

javascript 复制代码
// 假设有一个URL
var url = "https://www.example.com/index.html?name=John Doe";
// 使用encodeURI进行编码
var encodedUrl = encodeURI(url);
console.log(encodedUrl); // 输出编码后的URL:https://www.example.com/index.html?name=John%20Doe

在这个例子中,encodeURI会将URL中的非ASCII字符、空格等进行编码,但URL中的元字符(如冒号(:)、斜杠(/)、问号(?)等)不会被编码。

二、encodeURIComponent

encodeURIComponent函数主要用于编码URL的某个特定部分,如查询参数或路径段。它会编码所有的非字母数字字符,包括URL中的元字符。如果你想编码URL的一部分,而不是整个URL,应该使用encodeURIComponent。下面是一个使用encodeURIComponent的例子:

javascript 复制代码
// 假设有一个URL的一部分
var partOfUrl = "/index.html?name=John Doe";
// 使用encodeURIComponent进行编码
var encodedPartOfUrl = encodeURIComponent(partOfUrl);
console.log(encodedPartOfUrl); // 输出编码后的URL部分:%2Findex.html%3Fname%3DJohn%20Doe

在这个例子中,encodeURIComponent会将URL部分中的所有非字母数字字符进行编码,包括URL中的元字符。

总的来说,选择encodeURI还是encodeURIComponent取决于你的具体需求。如果你需要编码整个URL,那么你应该使用encodeURI。如果你只需要编码URL的一部分,那么你应该使用encodeURIComponent

三、解码

  1. decodeURI

    decodeURI函数用于解码整个URL。如果你之前使用了encodeURI对一个URL进行了编码,那么你可以使用decodeURI来将其解码回原始状态。

  2. decodeURIComponent

    decodeURIComponent函数用于解码URL的某个特定部分,如查询参数或路径段。如果你之前使用了encodeURIComponent对这些部分进行了编码,那么你可以使用decodeURIComponent来将其解码回原始状态。

相关推荐
码农诗人7 天前
C++调用ffmpeg解复用、解码案例
c++·ffmpeg·解码·解封装
伊织code8 天前
macOS 使用 enca 识别 文件编码类型(比 file 命令准确)
macos·文件·编码·file·iconv·enca
伊织code9 天前
macOS 使用 iconv 转化文件编码
macos·乱码·文件·编码·转换·iconv
HuggingFace20 天前
LayerSkip: 使用自推测解码加速大模型推理
大模型·解码·layerskip
星尘安全2 个月前
GitHub Copilot 越狱漏洞
人工智能·ai·copilot·编码·越狱
荣--2 个月前
HiJobQueue:一个简单的线程安全任务队列
c++·编码
羌芜3 个月前
对中文乱码的理解,遇到乱码该怎么办。
编码
core5124 个月前
一文说清flink从编码到部署上线
flink·部署·yarn·编码·cdc·guava30·guava18
H轨迹H4 个月前
2024御网杯信息安全大赛个人赛wp_2024-11-27
ctf·编码·misc
帅逼码农4 个月前
GRS码(Generalized Reed-Solomon Code)
编码·grs码