5

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 3

10
function decodeParameter(param) {
   return decodeURIComponent(param.replace(/\+/g, ' '));
}
Sign up to request clarification or add additional context in comments.

4 Comments

You need to do the plus-sign replace before the unescape, not after. Otherwise, real plus signs will get converted to spaces.
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.
@SimoneMelloni I've updated my answer. I know escape/unescape are deprecated, but look at the original response date ;)
2
"iPhone+4".replace("+"," ");  

That should do it?

1 Comment

Will only replace the first occurrence.
0

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," ");  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.