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>

    function myEncoding() {
        var u = "$%^&*()";
        var r = encodeURIComponent(u);
        document.getElementById("myId").innerHTML = r;

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 "$%^&*()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.


 Views: 728 | Post Order: 177

Write for us