URL encode and decode
URL encode
URL encoding is a process of converting characters and symbols into a format that is safe and can be used within a URL. URLs are composed of characters from a limited set (alphanumeric characters, hyphens, underscores, dots, and some special characters). URL encoding ensures that any special characters or non-ASCII characters in a URL are properly represented using a specific format, making the URL valid and accessible.
URL encoding is necessary when passing data through URLs, especially when the data contains characters that have special meanings in URLs, such as spaces, ampersands, question marks, or non-ASCII characters like accented letters.
For example, consider the URL:
https://example.com/search?q=my search query
Here, the space between "my" and "search" should be URL encoded to %20 to make the URL valid:
https://example.com/search?q=my%20search%20query
URL encoding replaces each character that needs to be encoded with a percentage sign followed by two hexadecimal digits that represent the character's ASCII code.
In JavaScript, you can use the encodeURIComponent() function to URL encode a string:
const encodedString = encodeURIComponent("my search query"); console.log(encodedString); // Output: "my%20search%20query"
In PHP, you can use the urlencode() function to URL encode a string:
$encodedString = urlencode("my search query"); echo $encodedString; // Output: "my%20search%20query"
URL encoding ensures that URLs are properly formatted and can be safely used in web applications without causing issues with special characters.