Javascript - 替换多个值 [英] Javascript - Replace more than one value
问题描述
我的脚本有问题.我想用 +
替换所有空格.
I have a problem with my script. I want to replace all spaces with +
.
脚本使用第一个空格,例如疯狗
:
The script works with the first space, e.g. for Crazy dog
:
Crazy+dog
但是使用第三个词它不再起作用,例如疯狗猫
:
But with a third word it does no longer work, e.g. for Crazy dog cat
:
Crazy+dog cat
我正在使用以下 JavaScript 代码:
I'm using the following JavaScript code:
function search() {
location.href = 'buscar/'+document.getElementById('appendedInputButton').value.replace(' ','+');
}
我搜索了如何做,但没有任何效果,我对 JavaScript 没有太多经验.
I searched how to do it, but nothing works me, I have not much experience with JavaScript.
很抱歉重新发布,我尝试使用 /.../
但它没有按预期工作.现在我知道了,我应该更多地使用 encodeURI
.
Sorry for the repost, I tried using the / ... /
but it did not work as expected. Now I know, I should be working more with encodeURI
.
推荐答案
最好的方法是使用带有 g
标志的正则表达式来替换所有出现的地方.
The best way is to use regular expression with g
flag to replace all occurrences.
<script type='text/javascript'>
function search()
{
location.href = 'buscar/'+document.getElementById('appendedInputButton').value.replace(/\s+/g, '+');
}
</script>
这篇关于Javascript - 替换多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!