What is URL Encoding in HTML?
URL encoding is a process of converting special characters and non-ASCII characters into a format that is compatible with URLs. It is necessary because URLs have specific requirements regarding the characters that can be used, for example, spaces, ampersands, and other special characters need to be encoded before they can be included in a URL.
How to use URL Encoding?
To use URL encoding in HTML, you can use the encodeURIComponent() JavaScript function or HTML entities.
Using JavaScript encodeURIComponent():
JavaScript provides the encodeURIComponent() function, which can be used to encode a string for safe inclusion in a URL. For more understanding see the below mentioned example:
<script>
var URL= 'https://example.com?param=' + encodeURIComponent('value with spaces & special characters');
console.log(URL);
</script>
According to the example, the encodeURIComponent() function is used to encode the value 'value with spaces & special characters' before appending it to the URL.
By using HTML Entities
HTML entities are special sequences of characters that represent specific characters. Some commonly used HTML entities for special characters include for a non-breaking space, < for <, > for >, etc. You can use HTML entities directly in your HTML markup, for example:
<a href="https://example.com?param=value%20with%20spaces%20%26%20special%20characters">
Link with encoded URL
</a>
according to the example, spaces are represented as %20, and the ampersand character is represented as %26. Actually, both methods will ensure that the URL is properly encoded and can be safely used within HTML. Choose the method that best suits your needs and programming context.