I try to extract parameter from URL, but one parameter has space which is replaced with "+", so the parameter I extract is "iphone+4", but actually it is "iphone 4", how can I convert to the second form, decodeURIComponent does not work here.
3 Answers
function decodeParameter(param) {
return decodeURIComponent(param.replace(/\+/g, ' '));
}
4 Comments
George
You need to do the plus-sign replace before the unescape, not after. Otherwise, real plus signs will get converted to spaces.
nickl-
Actually the characters * @ - _ + . / aren't affected by escape/unescape and this will still remove valid + signs in a url. encodeURI/decodeURI (which should actually be used for urls), has an even longer list of reserved characters ;/?:@=&# and special characters $-_.+!*'(), allowed as per RFC 1738, which will remain unchanged. By the looks of things this issue is still unresolved.
Simone Melloni
gion_13
@SimoneMelloni I've updated my answer. I know
escape/unescape are deprecated, but look at the original response date ;)"iPhone+4".replace("+"," ");
That should do it?
1 Comment
kapa
Will only replace the first occurrence.
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. 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," ");