为什么可以't〃;decodeURIComponent”;或“;decodeURI”;解码”;hello+wor

Why can't "decodeURIComponent" or "decodeURI" decode "hello+world" to "hello world" in JavaScript?

本文关键字:decodeURI hello+wor 解码 decodeURIComponent 为什么      更新时间:2023-09-26

据此:

http://en.wikipedia.org/wiki/Query_string#URL_encoding

"+"是有效的URL编码令牌。

如果是,为什么decodeURIComponentdecodeURI不能将"hello+world"解码为"helloworld"?

如果"+"是有效的,那么JavaScript中肯定有一个内置函数可以将"hello+world"转换为"helloworld"?

decideURIComponent的行为定义为encodeURIComponent:的"逆"运算

decodeURIComponent函数计算URI的新版本,其中encodeURIComponent函数可能引入的每一个转义序列和UTF-8编码都被它所表示的字符替换。

并且encodeURIComponent不是用+来代替空格,而是用%20来代替空格。

(类似于decodeURI

如果"+"是有效的,那么JavaScript中肯定有一个内置函数可以将"hello+world"转换为"helloworld"?

当然有:

"hello+world".replace(/'+/g, ' ');

因为encodeURIComponent会将空间编码为%20,所以您会得到hello%20world。如果您想替换+字符,我建议使用regex