The encodeURIComponent()
function encodes a URI component.
This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #
encodeURIComponent |
Yes | Yes | Yes | Yes | Yes |
encodeURIComponent(uri)
Parameter | Description |
---|---|
uri | Required. The URI to be encoded |
A String type value representing the encoded URI.
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.
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: