小能豆

Encode URL in JavaScript

js

How do you safely encode a URL using JavaScript such that it can be put into a GET string?

var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;

I assume that you need to encode the myUrl variable on that second line?


阅读 173

收藏
2023-12-26

共1个答案

小能豆

Yes, you are correct. To safely include a URL as a parameter in another URL, you should encode it using encodeURIComponent() in JavaScript. This function ensures that special characters in the URL are properly encoded, making it safe to include in a GET string.

Here’s how you can modify your code:

var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var encodedUrl = encodeURIComponent(myUrl);
var myOtherUrl = "http://example.com/index.html?url=" + encodedUrl;

In the above code, encodeURIComponent(myUrl) will replace special characters (such as :, /, ?, &, and others) with their URL-encoded equivalents, making myOtherUrl safe to use in a GET string.

2023-12-26