Encode URL in JavaScript?
Solution 1:
Check out the built-in function encodeURIComponent(str) and encodeURI(str).
In your case, this should work:
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
Solution 2:
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 escape
or encodeURIComponent
, but not encodeURI
.
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.