简体   繁体   English

如何使用javascript解码URL中的空格参数?

[英]How to decode parameter with space in URL using javascript?

我尝试从URL中提取参数,但是一个参数的空格被替换为“+”,所以我提取的参数是“iphone + 4”,但实际上它是“iphone 4”,我该如何转换为第二种形式,decodeURIComponent在这里不起作用。

function decodeParameter(param) {
   return decodeURIComponent(param.replace(/\+/g, ' '));
}
"iPhone+4".replace("+"," ");  

应该这样做吗?

It is an ambiguous thing, because you don't really know whether the + means a space or an actual plus sign. 这是一个含糊不清的东西,因为你不知道+是指空格还是实际的加号。 If you are also responsible for creating the URLs, you can solve this by using an appropriate URL encoding function which will use %20 to encode spaces. 如果您还负责创建URL,则可以使用适当的URL编码函数来解决此问题,该函数将使用%20来编码空格。 If you are just collecting them from somewhere else, well, you are left with the option of assuming that every + means a space :). 如果你只是从其他地方收集它们,那么你可以选择假设每个+意味着一个空间:)。

You can replace all + s using this code: 您可以使用以下代码替换所有+

your_text.replace(/\+/g," ");  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM