Javascript Reference - JavaScript encodeURI() Function








The encodeURI() function is used to encode a URI.

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

Browser Support

encodeURI Yes Yes Yes Yes Yes

Syntax

var v = encodeURI(uri)

Parameter Values

Parameter Description
uri Required. The URI to be encoded




Return Value

A String type value, representing the encoded URI.

Example

encodeURI() is used to encode URIs to be passed to the browser.

It is designed to work on an entire URI.

encodeURI() does not encode special characters that are part of a URI, such as the colon, forward slash, question mark, and pound sign


var uri = "http://www.java2s.com/illegal value.htm#start";
console.log(encodeURI(uri));

The code above generates the following result.

Example 2

The following code shows how to Encode a URI.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<!--   w  ww  .java 2s. c  om-->
<p id="demo"></p>

<script>
function myFunction() {
    var uri = "my test.asp";
    var res = encodeURI(uri);
    document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

The code above is rendered as follows: