0

I have to encode the string that I receive here and pass it as a URL parameter so I don't believe I can pass either / or a paranthesis ( so considering I have the following string

KEY WEST / Florida(FL)

I am trying the following

encodeURIComponent("KEY WEST / Florida(FL)")
"KEY%20WEST%20%2F%20Florida(FL)"

escape("KEY WEST / Florida(FL)")
"KEY%20WEST%20/%20Florida%28FL%29"

Neither of them are encoding the string which I can decode later in my code as the first one is keeping the () and the second one is keeping the /

How do I do this in one shot and at a later time decode it when needed?

Also it seems like escape() has been deprecated so which way to do the encoding is preferred?

p0tta
  • 1,461
  • 6
  • 28
  • 49
  • 1
    Where are you needing to decode it? The `encodeURIComponent` should put it in the format that backend servers should have pre-existing logic to know how to decode them. – Taplar Nov 10 '20 at 22:09
  • If `encodeURIComponent` leaves the `( )` alone, you can be confident that the characters do not need to be encoded; that's the whole point. – Pointy Nov 10 '20 at 22:17
  • It's not working for my application. The encoded string is not being recognized by my Angular router. If I enter a plain text like just Key West, it works fine though. – p0tta Nov 10 '20 at 23:14
  • Just added a little more detail on how it's breaking my AngularJS router when I try to pass the param using encodeURIComponent – p0tta Nov 12 '20 at 00:35

1 Answers1

2

For URL encoding, encodeURI and encodeURIComponent functions should be used.

encodeURI encodes only special characters, while encodeURIComponent also encodes characters that have a meaning in the URL, so it is used to encode query strings, for example.

Parentheses are (as explained here), however, allowed anywhere in the URL without encoding them, that's why encodeURIComponent leaves them as-is.

The escape function can be considered deprecated, and although it officially isn't, it should be avoided.


so which way to do the encoding is preferred?

Also see When are you supposed to use escape instead of encodeURI / encodeURIComponent?

FZs
  • 16,581
  • 13
  • 41
  • 50
  • So when I try to use either and pass it into my router, it's breaking the AngularJS routing and throwing a 404. I am passing it as param – p0tta Nov 12 '20 at 00:33
  • .when('/myedpoint/:param?', { templateUrl: 'components/test/testPage.html', controller: 'TestPageController' }) – p0tta Nov 12 '20 at 00:34
  • 1
    Accepting this answer as this is technically what I had asked for initially and this is a very accurate and elaborate answer but I created another ticket if you have the interest to take a look https://stackoverflow.com/questions/64797981/angularjs-url-parameter-returning-a-404-upon-encoding – p0tta Nov 12 '20 at 04:35