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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)