我想对我的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*
。所以,等等,*
发生了什么?为什么它没有被转换?简而言之:你实际上需要 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()
。
+
字符,那将会引起问题。 - user2428118"%2B"
并被replace
保留。 - MaxArtsearch.split(' ').map(encodeURIComponent).join('+')
- lowzhao