0

In a part of the code I can't change. The function encodeURIComponent() will be executed on the URL i pass in, how ever one of my API calls contains a + sign which is necessary to send as a + sign. Right now it gets replaces "%2B" which makes the API fail..

I have tried using escape and "%2B" and backslash infront of my + sign as "+" but nothing gives so far..

How do I make encodeURIComponent('+') return + and not "%2B"

Thank you affordtime for your help

Cisum Inas
  • 11,552
  • 11
  • 40
  • 55

4 Answers4

0

Temporarily swap out the plus signs for an arbitrary marker, e.g.

encodeURIComponent("one £ + £ two".replace(/\+/g, '*PLUS*')).replace('*PLUS*', '+');

Gives you:

"one%20%C2%A3%20+%20%C2%A3%20two"

...ie retains the +, which will also survive the reverse trip via decodeURIComponent().

Mitya
  • 33,629
  • 9
  • 60
  • 107
0

You can't do it without changing the code. encodeURIComponent will never output a + sign.

If you or someone else can change the code you could use this answer:

encodeURIComponent(search).replace(/%20/g, "+");

and then use spaces in the input where you want + to be.

Community
  • 1
  • 1
Paul
  • 139,544
  • 27
  • 275
  • 264
0

It is not usually recommended to overwrite native functions but you could do this which would redefined encodeURIComponent to not escape plus characters but otherwise escape the same set of characters.

function encodeURIComponent(s) {
    // encodeURI leaves these chars untouched @#$&=:/,;?+
    return encodeURI(s).replace(/[@#$&=:\/,;?]/g, function(c) {
        return '%'+c.charCodeAt(0).toString(16)
    })
}
PHP Guru
  • 1,301
  • 11
  • 20
0

As you can't change the behavior of encodeURIComponent, the simplest way is to replace %2B-s back to +-es:

encodeURIComponent('1+2=3').replace(/%2B/g, '+') //1+2%3D3

This is more efficient, as it needs a single replacement, and doesn't need intermediate "escaping", and simpler, as you don't have to reimplement encodeURIComponent and using the native one might be even faster for large strings.

FZs
  • 16,581
  • 13
  • 41
  • 50