Home > Software design >  Rails: how to escape "space" in Rails generated URL search string as instead of
Rails: how to escape "space" in Rails generated URL search string as instead of

Time:06-15

I have a search field in a Rails App. It is implemented this way:

<%= text_field_tag :searchAny, params[:searchAny_params], placeholder: "Search", id: "search_input", class: "search-field" %>
<%= submit_tag "Search", name: nil, id: "search-button", class: "search-button" %>

When I search for strings, which contain spaces such as: find something, I get find something in params, which is then rendered in the url as find something. To my knowledge spaces used to be escaped through , but now they should be escaped through .

I very much would like to switch to in my url, because I access the query string in my frontend in order to make it available to new search functions or parse it somewhere and would need the sign as a viable query string. Currently I am unable to search for house or , because the JS function I wrote splits the search string and currently has to replace with space.

var searchquery = searchParams.split('?').pop().split('&').pop().split('=')[1].replace(/[ ]/g, ' ');

After my refactoring I hope to get the search string part of my url with for space and leave available.

var searchquery = searchParams.split('?').pop().split('&').pop().split('=')[1].replace(/ /, ' ');

How can I change how params are escaped in the search string?

I hope someone can put me in the right direction. Thanks in advance.

Addition

Currently my Rails app produces the following URL:

https://www.domain.tld/collection/opac?searchAny=find something

I would prefer the query string to be already % escaped:

https://www.domain.tld/collection/opac?searchAny=find something

CodePudding user response:

Based on this answer from a similar question, you can use the Addressable gem. Or alternatively you can try using Javascript's encodeUri() to handle the URL encoding from the front-end side. For example:

document.getElementById('search_button').addEventListener('click', function() {
    var searchInput = document.getElementById("search_input");
    var encodedQuery = encodeURI(searchInput.value)
    // continue to use the encodedQuery as search query
});

Hope this helps!

  • Related