JavaScript encodeURIComponent和将空格转换为+符号

23

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

这是我尝试做的...

var search = "Testing this here &";

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

我的输出是Testing%2Bthis%2Bhere%2B%26,但我想要的是Testing+this+here+%26。我尝试用%20替换空格以将其转换为加号符号,但似乎没有起作用。有人能告诉我这里错在哪里吗?

2个回答

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

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


1
如果字符串包含任何“真正的” + 字符,那将会引起问题。 - user2428118
6
不,它不会。所有的“原始”加号都会转换为"%2B"并被replace保留。 - MaxArt
1
啊,我真傻,谢谢你。8分钟后我会选择你作为最佳答案。 - Ian
@user1419007,我一开始放了%2B而不是%20。但马上就纠正过来了。 - MaxArt
这可能会破坏多字节字符编码。 - Melab
我认为这也可以行得通?search.split(' ').map(encodeURIComponent).join('+') - lowzhao

1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接