20

我想对我的 URL 进行编码,但我想将空格转换为加号。

这就是我试图做的......

var search = "Testing this here &";

encodeURIComponent(search.replace(/ /gi,"+"));

输出结果是,Testing%2Bthis%2Bhere%2B%26但我希望它是Testing+this+here+%26我尝试用替换空格%20将其转换为加号,但这似乎不起作用。谁能告诉我我在这里做错了什么?

4

2 回答 2

50
encodeURIComponent(search).replace(/%20/g, "+");

您在这里做错的是首先将空格转换为加号,然后encodeURIComponent将加号转换为"%2B".

于 2012-06-01T21:30:23.467 回答
1

只是尝试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().

于 2020-06-18T21:27:03.877 回答