Javascript - Replace more than one value

2019-09-19 14:21发布

问题:

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

I'm using the following JavaScript code:

function search() {
    location.href = 'buscar/'+document.getElementById('appendedInputButton').value.replace(' ','+');
}

I searched how to do it, but nothing works me, I have not much experience with JavaScript.

Edit:

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.

回答1:

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>