javascript encodeURIComponent并将空格转换为+符号 [英] javascript encodeURIComponent and converting spaces to + symbols
问题描述
我想对我的网址进行编码,但我想将空格转换为加号。
I would like to encode my URL, but I want to convert spaces to plus symbols.
这就是我试图做的......
This is what I attempted to do...
var search = "Testing this here &";
encodeURIComponent(search.replace(/ /gi,"+"));
该输出是测试%2%这个%2Bhere%2B%26
但我希望它是测试+此+ +此处+%26
我尝试用%20替换空格
将其转换为加号,但这似乎不起作用。任何人都可以告诉我这是错在哪里吗?
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?
推荐答案
encodeURIComponent(search).replace(/%20/g, "+");
你在这里做错的是首先你将空格转换为加号,然后 encodeURIComponent
将加号转换为%2B
。
What you're doing wrong here is that first you convert spaces to pluses, but then encodeURIComponent
converts pluses to "%2B"
.
这篇关于javascript encodeURIComponent并将空格转换为+符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!