URL Encoding with encodeURIComponent

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?

  1. Prevent URL Breakage: Special characters like &, =, and spaces can break URLs. Encoding them ensures the URL remains valid.
  2. Example:
let name = "John Doe";
let url = "https://example.com?name=" + encodeURIComponent(name);
  1. Result: https://example.com?name=John%20Doe
  2. Correctly Pass Data in URLs: Dynamic values (e.g., user input) often contain special characters. Encoding them avoids errors.
  3. 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.

Leave a comment

Your email address will not be published. Required fields are marked *