Tuesday, May 22, 2018

Encode URL in JavaScript?




How do you safely encode a URL using JavaScript such that it can be put into a GET string?



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?


Answer



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);

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...