Altaf Altaf - 3 months ago 47
Javascript Question

encodeURIComponent algorithm source code

I am developing an application in titanium using Javascript. I need an open source implementation of

encodeURIComponent
in Javascript.

Can anybody guide me or show me some implementation?

Answer

The V8 implementation is available at line 327 of src/uri.js and is distributed under the BSD license.

// ECMA-262 - 15.1.3.4
function URIEncodeComponent(component) {
  var unescapePredicate = function(cc) {
    if (isAlphaNumeric(cc)) return true;
    // !
    if (cc == 33) return true;
    // '()*
    if (39 <= cc && cc <= 42) return true;
    // -.
    if (45 <= cc && cc <= 46) return true;
    // _
    if (cc == 95) return true;
    // ~
    if (cc == 126) return true;

    return false;
  };

  var string = ToString(component);
  return Encode(string, unescapePredicate);
}

It's not called encodeURIComponent there, but this code in the same file, esablishes the mapping:

InstallFunctions(global, DONT_ENUM, $Array(
    "escape", URIEscape,
    "unescape", URIUnescape,
    "decodeURI", URIDecode,
    "decodeURIComponent", URIDecodeComponent,
    "encodeURI", URIEncode,
    "encodeURIComponent", URIEncodeComponent
  ));

The specification for this function is in 15.1.3.4.