Saturday, May 04, 2013

How to encode a URL in JavaScript



encodeURI() function is used to encode a URI.

var encode_favourite= encodeURIComponent(favourite);

You have three options:

    escape() will not encode: @*/+

    encodeURI() will not encode: ~!@#$&*()=:/,;?+'

    encodeURIComponent() will not encode: ~!*()'

if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.

Example : 
<script>
var uri="my test.php?name=stale&car=lenova";
document.write(encodeURI(uri)+ "<br>");
</script> 


Tip: Use the decodeURI() function to decode an encoded URI.

No comments:

Post a Comment