Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中用%20替换空间?_Javascript - Fatal编程技术网

如何在javascript中用%20替换空间?

如何在javascript中用%20替换空间?,javascript,Javascript,可能重复: 我得到的sParameter是这样的: sParameter=document.getElementById('ddParameterType')。值 如果我得到类似于“Test-Text”的单词作为ddParameterType项,那么我将替换word中的空格,如下所示: sParameter=document.getElementById('ddParameterType').value.replace(“,“%20”) 但它返回的值类似于%20Test-Text我需要类似于测

可能重复:

我得到的sParameter是这样的:

sParameter=document.getElementById('ddParameterType')。值

如果我得到类似于
“Test-Text”
的单词作为ddParameterType项,那么我将替换word中的空格,如下所示:

sParameter=document.getElementById('ddParameterType').value.replace(“,“%20”)


但它返回的值类似于
%20Test-Text

我需要类似于
测试%20-%20Text
使用以下内容替换所有出现的值:

document.getElementById('ddParameterType').value.replace(/ /g, "%20");
或者更好:

将从字符串中删除前导和尾随空格
encodeURIComponent
将URL对其进行编码。

replace
replace(“,“%20”)替换为
替换(//g,“%20”)

 sParameter = encodeURIComponent(sParameter.trim())

存在encodeURI:很抱歉,我无法理解您需要对用户数据进行编码。有人能帮我理解原因吗?这个解决方案适用于IE和其他浏览器。ThanksenseCodeUriComponent()将http://更改为类似于http%3A%2F%2F的内容,并且它在浏览器上不起作用。encodeURI是保留http://协议的首选方法这是正确答案,但质量较差。正确的做法是使用
encodeURIComponent()
encodeURIComponent()将http://更改为类似http%3A%2F%2F的内容,并且它在浏览器上不起作用。这比公认的答案要好注意这不仅仅是空格。。。但这可能是件好事。
sParameter = encodeURIComponent(sParameter.trim()) //"Test%20-%20Text"
 sParameter = encodeURIComponent(sParameter.trim())