javascript encodeURIComponent 并将空格转换为 + 符号 [英] javascript encodeURIComponent and converting spaces to + symbols

查看:99
本文介绍了javascript encodeURIComponent 并将空格转换为 + 符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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,"+"));

它的输出是 Testing%2Bthis%2Bhere%2B%26 但我想要的是 Testing+this+here+%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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆