javascript encodeURIComponent and converting spaces to + symbols
Asked Answered
B

2

25

I would like to encode my URL, but I want to convert spaces to plus symbols.

This is what I attempted to do...

var search = "Testing this here &";

encodeURIComponent(search.replace(/ /gi,"+"));

The output from that is Testing%2Bthis%2Bhere%2B%26 but what I would like it to be is Testing+this+here+%26 I tried replacing the space with %20 to convert it into a plus symbol, but that didn't seem to work. Can anyone tell me what it is I'm doing wrong here?

Bish answered 1/6, 2012 at 21:29 Comment(0)
T
59
encodeURIComponent(search).replace(/%20/g, "+");

What you're doing wrong here is that first you convert spaces to pluses, but then encodeURIComponent converts pluses to "%2B".

Tarpeia answered 1/6, 2012 at 21:30 Comment(6)
That will cause problems if the string contains any "real" + characters.Sequestration
@user1419007 No it won't. All "original" pluses are converted to "%2B" and kept by replace.Tarpeia
Ah, silly me, thank you. I'll select you for best answer when the 8 minutes are up.Bish
@user1419007 I put %2B instead of %20 at first. Corrected right away.Tarpeia
This could break multi-byte character encodings.Mims
I think this could work too? search.split(' ').map(encodeURIComponent).join('+')Sigler
F
1

Just try encodeURI() and encodeURIComponent() yourself...

console.log(encodeURIComponent('@#$%^&*'));

Input: @#$%^&*. Output: %40%23%24%25%5E%26*. So, wait, what happened to *? Why wasn't this converted? TLDR: You actually want encodeRFC3986URIComponent() and encodeRFC3986URI(). Long-story...

Don't use encodeURIComponent() directly.

You should use encodeRFC3986URIComponent(), as indicated by the MDN Documentation. encodeURIComponent does not encode any of the following: !',()*. You need to use this other function. It will solve not only your space problems, but other character problems.

function encodeRFC3986URIComponent(str) {
  return encodeURIComponent(str).replace(
    /[!'()*]/g,
    (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
  );
}

console.log(encodeRFC3986URIComponent('@#$%^&*'));

To quote the MDN Documentation encodeURIComponent()...

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used: encodeRFC3986URIComponent().

Forney answered 18/6, 2020 at 21:27 Comment(1)
Looks like it doesn't exist anymore.Arris

© 2022 - 2024 — McMap. All rights reserved.