我想对我的 URL 进行编码,但我想将空格转换为加号。
这就是我试图做的......
var search = "Testing this here &";
encodeURIComponent(search.replace(/ /gi,"+"));
输出结果是,Testing%2Bthis%2Bhere%2B%26
但我希望它是Testing+this+here+%26
我尝试用替换空格%20
将其转换为加号,但这似乎不起作用。谁能告诉我我在这里做错了什么?
我想对我的 URL 进行编码,但我想将空格转换为加号。
这就是我试图做的......
var search = "Testing this here &";
encodeURIComponent(search.replace(/ /gi,"+"));
输出结果是,Testing%2Bthis%2Bhere%2B%26
但我希望它是Testing+this+here+%26
我尝试用替换空格%20
将其转换为加号,但这似乎不起作用。谁能告诉我我在这里做错了什么?
encodeURIComponent(search).replace(/%20/g, "+");
您在这里做错的是首先将空格转换为加号,然后encodeURIComponent
将加号转换为"%2B"
.
只是尝试encodeURI()
和encodeURIComponent()
你自己...
console.log(encodeURIComponent('@#$%^&*'));
输入:@#$%^&*
。输出:%40%23%24%25%5E%26*
。所以,等等,发生了什么事*
?为什么没有转换?TLDR:您实际上想要fixedEncodeURIComponent()
和fixedEncodeURI()
。很长的故事...
不要encodeURIComponent()
直接使用。
fixedEncodeURIComponent()
如 MDN 文档所示, 您应该使用。encodeURIComponent
不编码以下任何内容:!',()*
. 您需要使用此其他功能。它不仅可以解决您的空间问题,还可以解决其他性格问题。
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
引用 MDN 文档encodeURIComponent()
...
为了更严格地遵守 RFC 3986(保留 !、'、(、) 和 *),即使这些字符没有正式的 URI 定界用途,也可以安全地使用以下字符:
fixedEncodeURIComponent()
.