【问题标题】:Why can't "decodeURIComponent" or "decodeURI" decode "hello+world" to "hello world" in JavaScript? [duplicate]为什么“decodeURIComponent”或“decodeURI”不能在 JavaScript 中将“hello+world”解码为“hello world”? [复制]
【发布时间】:2015-05-07 21:57:49
【问题描述】:

据此:

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

“+”是一个有效的 URL 编码标记。

如果是这样,为什么decodeURIComponentdecodeURI 不能将“hello+world”解码为“hello world”?

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

【问题讨论】:

标签: javascript url urlencode urldecode


【解决方案1】:

The behavior of decideURIComponent is defined asencodeURIComponent的“逆”运算:

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

encodeURIComponent 不会用+ 替换空格,而是用%20

decodeURI 类似)

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

当然有:

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

【讨论】:

    【解决方案2】:

    因为encodeURIComponent 会将空格编码为%20,所以你会得到hello%20world。如果你想替换 + 字符我建议使用正则表达式

    【讨论】:

      猜你喜欢
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 2010-11-11
      相关资源
      最近更新 更多