2

Hello I have an input field on my site which people can enter search terms.

I am taking the value of the users input and spitting it out onto a url string.

jQuery("#searchButton").click(function(){
    var simpleSearchTermLocal = jQuery('#searchField').val();
    var urlString = "www.mysite.com/" + simpleSearchTermLocal;
    alert(urlString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchField" />
<button id="searchButton">search</button>

So when someone inputs something like "ABC" into the search field, the value of variable urlString becomes www.mysite.com/ABC which is fine.

But when entering a space in the input field, like "ABC 123", urlString becomes www.mysite.com/ABC 123 which isnt fine. I would like it to turn into www.mysite.com/ABC%20123

Any suggestions?

Thanks

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
cup_of
  • 6,397
  • 9
  • 47
  • 94

1 Answers1

4

You want the encodeURI() function.

var theString = "The quick brown fox jumped over the lazy dog.";

console.log(encodeURI(theString));
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71