In JavaScript, you can use the encodeURIComponent() function to encode a URL. This function takes a string as input and returns a new string in which certain characters have been replaced with their corresponding URL-encoded values.
Here's a simple example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>URL Encoding in JavaScript</title>
</head>
<body>
<script>
// Original URL
var originalUrl = "https://example.com/search?q=JavaScript&lang=en";
// Encode the URL
var encodedUrl = encodeURIComponent(originalUrl);
// Display the results
console.log("Original URL:", originalUrl);
console.log("Encoded URL:", encodedUrl);
</script>
</body>
</html>
In this example, the encodeURIComponent() function is used to encode the original URL. The results are then displayed in the console.
Please note that encodeURIComponent() is typically used to encode individual components of a URL, such as query parameters, rather than the entire URL. If you want to encode the entire URL, you can still use
encodeURIComponent(), but be aware that certain characters like
: and / will not be encoded, as they are allowed in the path of a URL.
If you specifically want to encode the entire URL, you can use encodeURI():
var encodedUrl = encodeURI(originalUrl);
Choose the appropriate encoding function based on your specific use case.
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In JavaScript, you can use the encodeURIComponent() function to encode a URL. This function takes a string as input and returns a new string in which certain characters have been replaced with their corresponding URL-encoded values.
Here's a simple example:
In this example, the encodeURIComponent() function is used to encode the original URL. The results are then displayed in the console.
Please note that encodeURIComponent() is typically used to encode individual components of a URL, such as query parameters, rather than the entire URL. If you want to encode the entire URL, you can still use encodeURIComponent(), but be aware that certain characters like : and / will not be encoded, as they are allowed in the path of a URL.
If you specifically want to encode the entire URL, you can use encodeURI():
Choose the appropriate encoding function based on your specific use case.