encodeURIComponent is a JavaScript function used to encode a URI component by escaping characters that might interfere with a URL, such as spaces, &, =, and ?. This ensures data is safely included in URLs.
encodeURIComponent(str);
str: The string to encode.- Returns a new string with special characters replaced by their encoded values.
Why Use encodeURIComponent?
- Prevent URL Breakage: Special characters like
&,=, and spaces can break URLs. Encoding them ensures the URL remains valid. - Example:
let name = "John Doe"; let url = "https://example.com?name=" + encodeURIComponent(name);
- Result:
https://example.com?name=John%20Doe - Correctly Pass Data in URLs: Dynamic values (e.g., user input) often contain special characters. Encoding them avoids errors.
- Enhance User Experience: Ensures that user data is safely passed in URLs without issues from special characters.
Example:
const POLIST_URL = "https://example.com?";
function goToList(access, userParam) {
let url = `${POLIST_URL}poid=${encodeURIComponent(access)}&user=${encodeURIComponent(userParam)}`;
window.location.href = url;
}
Use encodeURIComponent when adding dynamic data to URLs to ensure they remain safe and functional, avoiding issues caused by special characters.