I have a form with a text input with an id txtPlace that users will be entering input into that will be passed to the server as a url query. I'm trying to use encodeURIComponent(), but it is not encoding spaces. Here's my simplified code
<div class="searchBoxRow">
<input type="text" id="txtPlace" size="55" placeholder="Enter place to search"/>
<a href="#" id="btnSearch">Search</a>
</div>
Here is my javascript
<script type="text/javascript">
$(function () {
$('#btnSearch').on('click', function (e) {
e.preventDefault;
var place = encodeURIComponent($('#txtPlace').val());
var url = "http://example.com?place=" + place;
document.location.href = url;
});
});
</script>
If a user types ACME Co.,New York, NY, the generated url is
http://example.com?place=ACME Co.%2CNew York%2C NY
See the spaces are unencoded? I even tried to add place = place.replace(/\s/g, '+')
but that doesn't seem to work after encoding. What am I doing wrong? Thanks for your assistance.
Blame Firefox! Found out that the spaces were being properly encoded but Firefox is not displaying spaces as encoded even though they are. Tested in Internet Explorer 10 and Google Chrome and they both display spaces in their encoded format. Thanks Adam for the fiddle http://jsfiddle.net/VYDcv/
URLEncode() function. In JavaScript you can use the encodeURIComponent() function. Click the "URL Encode" button to see how the JavaScript function encodes the text. Note: The JavaScript function encodes space as %20.
encodeURIComponent should be used to encode a URI Component - a string that is supposed to be part of a URL. encodeURI should be used to encode a URI or an existing URL.
The difference between encodeURI and encodeURIComponent is encodeURIComponent encodes the entire string, where encodeURI ignores protocol prefix ('http://') and domain name. encodeURIComponent is designed to encode everything, where encodeURI ignores a URL's domain related roots.
The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
I'm not sure what you're seeing, but encodeURIComponent
does escape space characters.
See this fiddle, based on your code: http://jsfiddle.net/VYDcv/
If you type "Hello world", it will alert you with the space replaced by a %20
.
Alert results: http://example.com?place=Hello%20World
When you set your browser's document.location.href
, it may be changing the %20
back to a space in the address bar, but it IS being escaped by the javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With