Source code for the encodeURIComponent algorithm

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

Can someone help me or show me some implementation?

+5
javascript encoding titanium
source share
3 answers

The specification for this function is given in 15.1.3.4 .


Modern versions (2018) of V8 implement it in C ++. See Src / uri.h :

 // ES6 section 18.2.6.5 encodeURIComponenet (uriComponent) static MaybeHandle<String> EncodeUriComponent(Isolate* isolate, Handle<String> component) { 

which calls Encode defined in uri.cc.


Older versions of V8 implemented it in JavaScript and distributed under the BSD license. See Line 359 from src / uri.js.

 // 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 is not called encodeURIComponent there, but this code in the same file, esablishes display:

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

Why do you need an encoder? He is already present in JS.

In any case, here is an example implementation:

http://phpjs.org/functions/rawurlencodecode0101comment_93984

0
source share

Here is my implementation:

 var encodeURIComponent = function( str ) { var hexDigits = '0123456789ABCDEF'; var ret = ''; for( var i=0; i<str.length; i++ ) { var c = str.charCodeAt(i); if( (c >= 48/*0*/ && c <= 57/*9*/) || (c >= 97/*a*/ && c <= 122/*z*/) || (c >= 65/*A*/ && c <= 90/*Z*/) || c == 45/*-*/ || c == 95/*_*/ || c == 46/*.*/ || c == 33/*!*/ || c == 126/*~*/ || c == 42/***/ || c == 92/*\\*/ || c == 40/*(*/ || c == 41/*)*/ ) { ret += str[i]; } else { ret += '%'; ret += hexDigits[ (c & 0xF0) >> 4 ]; ret += hexDigits[ (c & 0x0F) ]; } } return ret; }; 
0
source share

All Articles