2

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 isn't fine. I would like it to turn into www.mysite.com/ABC%20123.

How can I achieve this?

0

1 Answer 1

4

You want the encodeURI() function.

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

console.log(encodeURI(theString));

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome this is the answer, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.