javascript encodeURIComponent 并将空格转换为 + 符号

标签 javascript regex replace encodeuricomponent

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

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

var search = "Testing this here &";

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

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

最佳答案

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

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

关于javascript encodeURIComponent 并将空格转换为 + 符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10857590/

相关文章:

javascript - 使用jquery获取rails中每个 block 中元素的动态id

javascript - 如何重新加载javascript代码块

javascript - 在 javascript 中解析 m3u8 正则表达式

正则表达式在字符串中查找单词,替换新字符串中的单词(使用 Notepad++)

javascript - jquery 数组未获取所有值且未发送到 laravel Controller

javascript - Angular2 systemjs.config.js ' "引用错误 : System is not defined"

php - preg_match_all : Why would "this" match but "that" won't?

c++ - 用于提取括号内所有内容的正则表达式

xml - 用于查找和替换的 Xpath?

php - 通过 id 查找元素并将其内容替换为 php