9

Currently, when I pass my query string into the search() method of $location, my query string is uri encoded

Example

$location.path('/some_path').search({'ids[]': 1})

becomes

http://some_url/some_path?ids%5B%5D=1

I wonder if there's a way to get around this?

10
  • I want to have the param name semantically defined instead of using something like a comma separated list. Commented Jan 31, 2014 at 6:40
  • 1
    There is a way around this, but the more important question is, should you? Special characters should be encoded in a URL. If you don't want to show it's 'ugliness' use a post instead of a get. Commented Apr 29, 2014 at 5:49
  • 2
    What is your reason for this? Even if you come up with one good one, there's a million others that oppose it. Regardless of how AngularJS encodes the URL, when $location.search() is called it un-encodes the URL back into your original object. At this point, the only reason for doing what you're trying to do is to make the URL look prettier in the browser. Commented Apr 30, 2014 at 18:25
  • 2
    @Mike can you name few of the million reasons, please? :) Commented May 3, 2014 at 22:15
  • 1
    possible duplicate of AngularJS: avoid url encoding with $location Commented Apr 23, 2015 at 21:36

1 Answer 1

3

The problem is that .search() uses encodeUriQuery that internally uses encodeURIComponent and this function escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

The current function inside Angular's source code:

/**
 * This method is intended for encoding *key* or *value* parts of query component. We need a custom
 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
 * encoded per http://tools.ietf.org/html/rfc3986:
 *    query       = *( pchar / "/" / "?" )
 *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
 *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
 *    pct-encoded   = "%" HEXDIG HEXDIG
 *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
 *                     / "*" / "+" / "," / ";" / "="
 */
function encodeUriQuery(val, pctEncodeSpaces) {
  return encodeURIComponent(val).
             replace(/%40/gi, '@').
             replace(/%3A/gi, ':').
             replace(/%24/g, '$').
             replace(/%2C/gi, ',').
             replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}

If that function had this additional replaces, then the brackets will keep unencoded:

replace(/%5B/gi, '[').
replace(/%5D/gi, ']').
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.