0

If my URI-component (say a value for a query-string parameter) is a complete URL, should I use encodeURI() or encodeURIComponent()? OR BOTH like this: encodeURIComponent ( encodeURI (theCompleteURI )) ?

In other words does one of them also do the job of the other so I could just use one of them?

I'm also a bit confused as to why we need encodeURI() at all. If I enter a URL to the browser's location field should it not do the needed conversions for me? Or if I call a Node.js http-client library function should that not do the same as well?

The reason for encoding a URL would be so I can embed it as a query string value of a complete URL without breaking the containing URL I will then make the request for. But then shouldn't encodeURIComponent() be all that I need?

So I guess the 2nd part of my question is why should I use encodeURI(), when?

Is there a reason why encodeURI() could not also encode all its components? Or could I create my own version of it say encodeURI2() which does it all? Would it not make sense to have such a function built-in if it is possible?

Panu Logic
  • 2,193
  • 1
  • 17
  • 21
  • Possible duplicate of [Should I use encodeURI or encodeURIComponent for encoding URLs?](https://stackoverflow.com/questions/4540753/should-i-use-encodeuri-or-encodeuricomponent-for-encoding-urls) – Brandon Aug 01 '18 at 18:51
  • I understand this is almost a duplicate of related question(s) asked earlier but my question is specifically about how to handle a URI-component which is also a complete URL Do I need to call BOTH encodeUriComponent() and encodeURI() to get the result that can be used as a URL, and under which circumstances. This is a complicated topic so I think it's important to be very specific about the question(s) being asked. – Panu Logic Aug 01 '18 at 19:00
  • the 2nd answer in that question is *exactly* the answer to your question – Brandon Aug 01 '18 at 19:01
  • I would say it is a good answer but somewhat ambiguous because it answers if A then X and if B then Y, but it does not specifically answer what if BOTH A and B?. It may be the right answer but it is an answer to a somewhat different question. – Panu Logic Aug 01 '18 at 19:12
  • `'http://example.com/foo?bar=' + encodeURIComponent('http://example.com/blah?baz=doh')` – Salman A Aug 01 '18 at 19:38

0 Answers0