In HTML, you can use the `encodeURIComponent()` JavaScript function to URL encode a string. Here's an example of how to use it:
<!DOCTYPE html>
<html>
<head>
<title>URL Encoding Example</title>
<script>
function encodeURL() {
var input = document.getElementById("input").value;
var encoded = encodeURIComponent(input);
document.getElementById("encoded").textContent = encoded;
}
</script>
</head>
<body>
<h2>URL Encoding Example</h2>
<input type="text" id="input" placeholder="Enter a URL">
<button onclick="encodeURL()">Encode</button>
<p>Encoded URL: <span id="encoded"></span></p>
</body>
</html>
In the example above, there is an input field where you can enter a URL. When you click the "Encode" button, the `encodeURL()` function is triggered. It retrieves the input value, encodes it using `encodeURIComponent()`, and displays the encoded URL in the `<span>` element with the id "encoded".
For instance, if you enter "https://example.com/?param=value" in the input field, the encoded URL will be displayed as "https%3A%2F%2Fexample.com%2F%3Fparam%3Dvalue".
Note that `encodeURIComponent()` encodes all characters that are not unreserved characters in the URL specification (RFC3986). This includes characters like spaces, punctuation, and non-ASCII characters. If you want to encode a complete URL including reserved characters, you can use the `encodeURI()` function instead.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc