The DrupalencodeURIComponent function

Earlier, we looked at encoding HTML with Drupal.checkPlain(). Here, we will look at another encoding function—one designed for encoding pieces of a URL or URI.

Drupal PHP programmers may also recognize this function. It essentially performs the same task as the drupal_urlencode() PHP function. Those familiar with JavaScript will recognize this as having the same name as a built-in JavaScript function.

The built-in JavaScript function, encodeURicomponent(), is used to encode values that will be used when constructing a query string or a URI. Certain values, such as a slash (/), have special meaning in URLs. A slash indicates a directory.

How do we write a request for a document on the server named pros/cons, html, where the slash is part of the file name and not an indicator that pros/ is a directory? It should be escaped with "/" replaced by a hexadecimal representation of the character. We can see how this is done with the built-in browser function encodeURIComponent() :

>>> encodeURIComponent('pros/cons.html'); "pros%2Fcons.html"

Looking at the Firebug output, we can see that the slash was replaced by %2F, where 2F is the ASCII hexadecimal representation of the / character.

But Drupal presents something of a special case. It uses paths as query parameters. So we would expect strings, such as node/1/edit with the slashes left as is. At the same time, we would want other special characters, such as %, to be escaped correctly.

That's where Drupal.encodeURIComponent() comes in. It correctly converts other characters while preserving the slashes. To see this in action, let's compare how the two different functions convert the fiction link node/i/calc%:

>>> myString = 'node/1/calc%'; "node/1/calc%"

>>> encodeURIComponent(myString); "node%2F1%2Fcalc%2 5"

>>> Drupal.encodeURIComponent(myString); "node/1/calc%25"

In this example we can see the difference: The Drupal.encodeURIComponent() call preserved the slashes in the path.

In general, Drupal.encodeURIComponent() should be used any time you are constructing links back to Drupal. However, when making calls to other non-Drupal services, you should continue to use the browser-defined encodeURIComponent() function.

Was this article helpful?

+1 0

Post a comment