如何使用JavaScript安全地编码URL,以便将其放入GET字符串中?

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

我假设您需要在第二行编码myUrl变量?


当前回答

什么是URL编码:

当URL中有特殊字符时,应对URL进行编码。例如:

console.log(encodeURIComponent('?notEncoded=&+'));

我们可以在这个例子中观察到,除了字符串notEncoded之外的所有字符都用%符号编码。URL编码也称为百分比编码,因为它用%转义所有特殊字符。然后在这个%符号之后,每个特殊字符都有一个唯一的代码

为什么我们需要URL编码:

某些字符在URL字符串中具有特殊值。例如?字符表示查询字符串的开头。为了在web上成功定位资源,必须区分字符是字符串的一部分还是URL结构的一部分。

如何在JavaScript中实现URL编码:

JavaScript提供了一系列内置实用程序函数,我们可以使用这些函数轻松地对URL进行编码。有两个方便的选项:

encodeURIComponent():将URI的一个组件作为参数,并返回编码的URI字符串。encodeURI():将URI作为参数并返回编码的URI字符串。

示例和警告:

注意不要将整个URL(包括方案,例如https://)传递到encodeURIComponent()中。这实际上可以将其转换为不起作用的URL。例如:

//对于整个URI,不要使用encodeURIComponent,它将转换///字符和URL不能正常工作console.log(encodeURIComponent(“http://www.random.com/specials&char.html"));//而是对整个URL使用encodeURIconsole.log(encodeURI(“http://www.random.com/specials&char.html"));

我们可以观察到,如果我们将整个URL放在encodeURIComponent中,正斜杠(/)也会转换为特殊字符。这将导致URL不再正常运行。

因此(顾名思义)使用:

encodeURIComponent位于要编码的URL的特定部分。要编码的整个URL上的encodeURI。

其他回答

现代解决方案(2021)

自从编写了其他答案后,就引入了URLSearchParams API。它可以这样使用:

const queryParams = { param1: 'value1', param2: 'value2' }
const queryString = new URLSearchParams(queryParams).toString()
// 'param1=value1&param2=value2'

它还编码非URL字符。

对于您的具体示例,您可以这样使用:

常量myUrl=“http://example.com/index.html?param=1&anotherParam=2";const myOtherUrl=新URL(“http://example.com/index.html");myOtherUrl.search=新URLSearchParams({url:myUrl});console.log(myOtherUrl.toString());

这个解决方案也在这里和这里提到。

查看内置函数encodeURIComponent(str)和encodeURI(str)。在您的情况下,这应该有效:

var myOtherUrl = 
       "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

我用普通JavaScript做了类似的尝试:

function fixedEncodeURIComponent(str){
    return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

为了防止双重编码,最好在编码之前解码URL(例如,如果您处理的是用户输入的URL,可能已经编码)。

假设我们有abc%20xyz 123作为输入(一个空格已编码):

encodeURI("abc%20xyz 123")            //   Wrong: "abc%2520xyz%20123"
encodeURI(decodeURI("abc%20xyz 123")) // Correct: "abc%20xyz%20123"

不要忘记用/g标志替换所有编码的“”

var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl).replace(/%20/g,'+');