var myUrl = "http://example.com/index.html?param=1&anotherParam=2"; var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
I assume that you need to encode the
myUrl variable on that second line?
You have three options:
escape()will not encode:
encodeURI()will not encode:
encodeURIComponent()will not encode:
But in your case, if you want to pass a URL into a
GET parameter of other page, you should use
encodeURIComponent, but not
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
encodeURIComponent(). The function
encodeURI() does not bother to encode many characters that have semantic importance in URLs (e.g. “#”, “?”, and “&”).
escape() is deprecated, and does not bother to encode “+” characters, which will be interpreted as encoded spaces on the server (and, as pointed out by others here, does not properly URL-encode non-ASCII characters).
There is a nice explanation of the difference between
encodeURIComponent() elsewhere. If you want to encode something so that it can safely be included as a component of a URI (e.g. as a query string parameter), you want to use