How to percent-encode Strings with JavaScript?

Estimated read time 1 min read

To percent-encode a string in JavaScript, you can use the encodeURIComponent() function. This function takes a string as input and returns a new string with all reserved characters replaced with their percent-encoded equivalents. Reserved characters are those with a special meaning in a URL, such as spaces, ampersands, and question marks.

Here’s an example:

const string = 'Hello, world! How are you?';
const encoded = encodeURIComponent(string);

console.log(encoded);
// Output: 'Hello%2C%20world%21%20How%20are%20you%3F'

In this example, the encodeURIComponent() function is used to percent-encode the string. The resulting encoded string contains all reserved characters replaced with their percent-encoded equivalents. For example, the space character is replaced with %20, the comma is replaced with %2C, and the question mark is replaced with %3F.

Note that there is a corresponding decodeURIComponent() function that can be used to decode a percent-encoded string back into its original form.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply