Read more

Escape a string for transportation in a URL

Henning Koch
September 24, 2015Software engineer at makandra GmbH

To safely transport an arbitrary string within a URL, you need to percent-encode Show archive.org snapshot characters that have a particular meaning in URLs, like & or =.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

If you are using Rails URL helpers like movies_path(:query => ARBITRARY_STRING_HERE), Rails will take care of the encoding for you. If you are building URLs manually, you need to follow this guide.

Ruby

In Ruby, use CGI.escape:

CGI.escape('foo=foo&bar=bar')
=> "foo%3Dfoo%26bar%3Dbar"

Do not ever use URI.encode or its alias URI.escape, which keeps control characters like & or = unescaped:

URI.encode('foo=foo&bar=bar')
=> "foo=foo&bar=bar"

Javascript

In Javascript, use encodeURIComponent:

encodeURIComponent('foo=foo&bar=bar')
=> "foo%3Dfoo%26bar%3Dbar"

Do not ever use encodeURI, which keeps control characters like & or = unescaped:

encodeURI('foo=foo&bar=bar')
=> "foo=foo&bar=bar"
Posted by Henning Koch to makandra dev (2015-09-24 14:53)