-1

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.

ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
Kokox
  • 519
  • 1
  • 9
  • 24
  • 3
    Try replacing with `/ /g`. Or try `encodeURIComponent` – elclanrs Feb 01 '14 at 01:33
  • 2
    Looks like you have not searched a lot... http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript – dbermudez Feb 01 '14 at 01:35
  • possible duplicate of [Fastest method to replace all instances of a character in a string](http://stackoverflow.com/questions/2116558/fastest-method-to-replace-all-instances-of-a-character-in-a-string) – Dennis Feb 01 '14 at 01:36
  • When working with a URL you should url encode it, not replace characters. – adeneo Feb 01 '14 at 01:38

1 Answers1

0

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>
eltyweb
  • 91
  • 1
  • 2