Open In App

How do we use the encodeURIComponent() function in JavaScript ?

Last Updated : 30 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The encodeURIComponent() function in JavaScript is used to encode special characters in a URL, ensuring that the resulting string can be safely included as a component of a URL without causing issues. This function is particularly useful when you need to construct query parameters or other parts of a URL that may contain reserved characters.

Example: Here, spaces are replaced with %20, commas with %2C, exclamation marks with %21, and question marks with %3F. This ensures that the resulting encodedInput is a URL-safe representation of the original string.

Javascript




const userInput =
    'Hello, World! How are you?';
 
// Using encodeURIComponent to encode
// the user input for a URL
const encodedInput = encodeURIComponent(userInput);
 
console.log(encodedInput);
// Output: Hello%2C%20World%21%20How%20are%20you%3F


Output

Hello%2C%20World!%20How%20are%20you%3F

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads