How to interpret "+" as space in the url?

2

Well, I have the search page on my site, and when the initial form searches, you type "stack overflow" as a search, and in the url it gets stack + overflow instead of stack% 20overflow. Can you interpret "+" as "space" and +% 2B as "+" using javascript?

    
asked by anonymous 08.12.2014 / 00:50

1 answer

2

You can use window.location combined with encodeURIComponent

Example with window.location :

<form id="search-form" action="" method="GET">
<input type="text" id="search-box">
<input type="submit" value="buscar">
</form>
<script>
    (function() {
        var searchForm = document.getElementById("search-form");
        var searchBox = document.getElementById("search-box");
        searchForm.onsubmit = function () {
            window.location = "busca?query=" + encodeURIComponent(searchBox.value);
            return false;//Isto previne o redirecionamento "nativo" do form
        };
    })();
</script>

Example with alert (to see the result) :

var searchForm = document.getElementById("search-form");
var searchBox = document.getElementById("search-box");
searchForm.onsubmit = function () {
    alert(encodeURIComponent(searchBox.value));
    return false;//Isto previne o redirecionamento "nativo" do form
};
<form id="search-form" action="" method="GET">
	<input type="text" value="a+b+c+d+e+f" id="search-box">
	<input type="submit" value="buscar">
</form>
  

Note that encodeURI is different from encodeURIComponent

    
08.12.2014 / 01:05