javascript encodeURIComponent 并将空格转换为 + 符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10857590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript encodeURIComponent and converting spaces to + symbols
提问by Ian
I would like to encode my URL, but I want to convert spaces to plus symbols.
我想对我的 URL 进行编码,但我想将空格转换为加号。
This is what I attempted to do...
这就是我试图做的......
var search = "Testing this here &";
encodeURIComponent(search.replace(/ /gi,"+"));
The output from that is Testing%2Bthis%2Bhere%2B%26
but what I would like it to be is Testing+this+here+%26
I tried replacing the space with %20
to convert it into a plus symbol, but that didn't seem to work. Can anyone tell me what it is I'm doing wrong here?
它的输出是Testing%2Bthis%2Bhere%2B%26
但我希望它是Testing+this+here+%26
我尝试将空格替换%20
为将其转换为加号,但这似乎不起作用。谁能告诉我我在这里做错了什么?
回答by MaxArt
encodeURIComponent(search).replace(/%20/g, "+");
What you're doing wrong here is that firstyou convert spaces to pluses, but then encodeURIComponent
converts pluses to "%2B"
.
您在这里做错的是,首先将空格转换为加号,然后encodeURIComponent
将加号转换为"%2B"
.
回答by pete
You're using the wrong function. Use escape
instead of encodeURIComponent
.
您使用了错误的功能。使用escape
代替encodeURIComponent
。
var search = "Testing this here &";
console.log(escape(search.replace(/ /gi,"+")));?