这两种方法中应该使用哪一种来编码url ?
当前回答
如果要对字符串进行编码以放入URL组件(querystring参数),则应该调用encodeURIComponent。
如果您正在对一个现有URL进行编码,请调用encodeURI。
其他回答
encodeURI和encodeURIComponent的区别:
encodeURIComponent(value)主要用于编码queryString参数值,它对value中每个适用的字符进行编码。encodeURI忽略协议前缀(http://)和域名)。
在非常非常罕见的情况下,当你想实现手动编码来编码额外的字符时(尽管在典型情况下不需要编码),例如:!*,则 你可以用:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
(源)
这取决于你真正想做什么。
encodeURI假设输入是一个完整的URI,其中可能包含一些需要编码的字符。
encodeURIComponent将编码具有特殊含义的所有内容,因此您可以将它用于uri的组件,例如
var world = "A string with symbols & characters that have special meaning?";
var uri = 'http://example.com/foo?hello=' + encodeURIComponent(world);
As a general rule use encodeURIComponent. Don't be scared of the long name thinking it's more specific in it's use, to me it's the more commonly used method. Also don't be suckered into using encodeURI because you tested it and it appears to be encoding properly, it's probably not what you meant to use and even though your simple test using "Fred" in a first name field worked, you'll find later when you use more advanced text like adding an ampersand or a hashtag it will fail. You can look at the other answers for the reasons why this is.
如果要对字符串进行编码以放入URL组件(querystring参数),则应该调用encodeURIComponent。
如果您正在对一个现有URL进行编码,请调用encodeURI。
以下是摘要。
Escape()不会编码@ * _ + -。/ 不要使用它。 encodeURI()不会编码A-Z A-Z 0-9;, / ?: @ & = + $ - _。! ~ * ' () # 当你的输入是一个完整的URL,如“https://searchexample.com/search?q=wiki”时使用它 encodeURIComponent()不会编码A-Z A-Z 0-9 - _。! ~ * ' () 当您的输入是完整URL的一部分时使用它 如 const queryStr = encodeURIComponent(someString)