JavaScript > Global Reference

Encoding URI in JavaScript

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


By using encodeURI() function we can encode a uniform resource identifier (URI).

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

<script>
    function myEncoding() {
        var u = "the .NET Inetrview preparation videos?_#$%^&*()";
        var r = encodeURI(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 value "the .NET Inetrview preparation videos?_#$%^&*()" to the variable u, we need to encode the u variable, for that we are using encodeURI() function in Variable r. Onclick of the button "Encode" in the HTML code fires the function myEncoding() in the <script> block at the same type encodeURI() function encodes the string value and returns as output.

OUTPUT

 Views: 739 | Post Order: 175



Write for us