在 javascript 中编码 url 不编码 &

encoding url in javascript not encoding &

我在 javascript

中对以下字符串进行编码
encodeURI = "?qry=M & L";

这给我一个输出

qry=m%20&%20l

所以 M & L 中的“&”没有被编码。我该怎么办?

Does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI "scheme" can possibly contain.

Reference

encodeURI 不会对以下特殊字符进行编码

A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

let uri = "?qry=M & L"

console.log(encodeURI(uri))

所以你可以使用 encodeURIComponent ,这将编码除这些

之外的所有字符
A-Z a-z 0-9 - _ . ! ~ * ' ( )

let uri = "?qry=M & L"

console.log(encodeURIComponent(uri))

encodeURI() is not going to encode & as it will only encode certain set of special characters. to encode & you need to use encodeURIComponent.

encodeURI 编码所有内容,除了:

A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

encodeURIComponent 编码所有内容,除了:

A-Z a-z 0-9 - _ . ! ~ * ' ( )

console.log(encodeURIComponent("?qry=M & L"));

请注意这两种方法在用于对 URL 进行编码时的区别。

const URL = "https://www.example.com/resource?query=10&id=20&name=hello%"

console.log(encodeURI(URL));
console.log(encodeURIComponent(URL));

来自 MDN:

Note that encodeURI by itself cannot form proper HTTP GET and POST requests, such as for XMLHTTPRequests, because "&", "+", and "=" are not encoded, which are treated as special characters in GET and POST requests. encodeURIComponent, however, does encode these characters

改为使用 encoreURIComponent 将 & 编码为 %26,如下所示。 但它也编码其他特殊字符,如 ?=

let uri = "?qry=M & L"

console.log(encodeURIComponent(uri))

来自here

encodeURI() 函数用于对 URI 进行编码。

此函数对特殊字符进行编码,除了:, / ? : @ & = + $ # (使用 encodeURIComponent() 对这些字符进行编码).

并且,另见 this answer

因此,您可能必须执行类似

的操作
var inputWithSplChars = "M & L";
encodeURI  = "?qry=" + encodeURIComponent(inputWithSplChars);

希望对您有所帮助!干杯!

您应该使用 encodeURIComponent() 而不是 encodeURI()

Note: Usually encodeURIComponent() is used to encode a string (query string), that would be put to the URL. If you are using an existing URL to be encoded, then you may use encodeURI()

const uri = "?qry=M & L";

console.log(encodeURIComponent(uri));

参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

此处参考:url encode 您有三个选择:

escape(str) will not encode: * @ - _ + . /
encodeURI(uri) will not encode: ~!@#$&*()=:/,;?+'
encodeURIComponent(uri) will not encode: ~!*()'