• Register
Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Encode URL in JavaScript?

0 votes
93 views
How do you encode URL in JavaScript?
 
 
I want to encode above url. Please help me to encode url.
asked Nov 3, 2015 in JavaScript by Joy

1 Answer

+1 vote

Javascript provides us two method like: encodeURI() and encodeURIComponent().

The encodeURI() function is used to encode a URI. This function encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).

Code:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
    function doEncode(){
        var myUrl = "http://example.com/index.html?param1=1&param2=2";
        var endcodedUurl = encodeURIComponent(myUrl);
        document.getElementById('encodeURLDiv').innerHTML = endcodedUurl;
    }
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Java script encode url example</title>
</head>

<body>
    <h1>URL: http://example.com/index.html?param1=1&amp;param2=2</h1>
    <a href="" onClick="doEncode(); return false;">Encode URL</a>
    <h2>Encode URL: <div id="encodeURLDiv"></div></h2>
</body>
</html>


Output:-  Before output of URL Encode

Before url encode

After encode see the output of encoded url:

Encoded url

 

answered Nov 4, 2015 by john12 (2,960 points)
...