• Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

165
Views
Rails: how to escape "space" in Rails generated URL search string as %20 instead of +

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 %20.

I very much would like to switch to %20 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 %20 for space and leave + available.

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

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%20something
9 months ago · Santiago Gelvez
1 answers
Answer question

0

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!

9 months ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.