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?

4
  • 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. Commented Nov 10, 2020 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. Commented Nov 10, 2020 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. Commented Nov 10, 2020 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 Commented Nov 12, 2020 at 0:35

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

3 Comments

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
.when('/myedpoint/:param?', { templateUrl: 'components/test/testPage.html', controller: 'TestPageController' })
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 stackoverflow.com/questions/64797981/…

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.