JavaScript > Global Reference

Encoding URI component in JavaScript

How to encode a uniform resource identifier (URI) component in JavaScript?


By using encodeURIComponent() we can encode a uniform resource identifier (URI) component.

<p>Click the below button to Encode URI component.</p>
<input type="button" onclick="myEncoding()" value="Encode URI component">
<p id="myId"></p>

<script>
    function myEncoding() {
        var u = "http://www.dotnetfunda.com/advices/show/1125/9-years-stagnant-career-and-looking-of-job-in-dot-net-platform?_#$%^&*()";
        var r = encodeURIComponent(u);
        document.getElementById("myId").innerHTML = r;
    }
</script>

In the above code snippet we have given Id as "myId"to the second <p> element in the HTML code. There is a function myEncoding() in the<script>block which is connected to the onclick of the HTML button and there is a string with component "http://www.dotnetfunda.com/advices/show/1125/9-years-stagnant-career-and-looking-of-job-in-dot-net-platform?_#$%^&*()to the variable u, we need to encode the component of  u variable, for that we are using encodeURIComponent() function in Variable r Onclick of the button "Encode URI Component" in the HTML code fires the function myEncoding() in the <script> block at the same type encodeURIComponent() function encodes the string component and returns as output.

OUTPUT

 Views: 8038 | Post Order: 177



Write for us






Hosting Recommendations