How do we use the encodeURIComponent() function in JavaScript ?
Last Updated :
30 Jan, 2024
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?' ;
const encodedInput = encodeURIComponent(userInput);
console.log(encodedInput);
|
Output
Hello%2C%20World!%20How%20are%20you%3F
Share your thoughts in the comments
Please Login to comment...