Javascript Reference - JavaScript encodeURIComponent() Function








The encodeURIComponent() function encodes a URI component.

This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #

Browser Support

encodeURIComponent Yes Yes Yes Yes Yes

Syntax

encodeURIComponent(uri)

Parameter Values

Parameter Description
uri Required. The URI to be encoded




Return Value

A String type value representing the encoded URI.

Example

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

encodeURIComponent() is designed to work solely on a segment of a URI.

encodeURIComponent() encodes every nonstandard character.


var uri = "http://www.java2s.com/illegal value.htm#start";
console.log(encodeURIComponent(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>
<!--   www.j  av a  2s.  co m-->
<p id="demo"></p>

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

The code above is rendered as follows: