Skip to content

Instantly share code, notes, and snippets.

@jcubic
Created May 18, 2016 15:07
Show Gist options
  • Save jcubic/49fbff54d2e852e516797c3b34c92117 to your computer and use it in GitHub Desktop.
Save jcubic/49fbff54d2e852e516797c3b34c92117 to your computer and use it in GitHub Desktop.
Escape String as per EcmaScript spec
/*
* implementation of the alorithm from EcmaScript spec in section 15.1.2.4
* http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf
*/
(function(global) {
var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./,';
global.escapeString = function(str) {
str = str.toString();
var len = str.length, R = '', k = 0, S, chr, ord;
while(k < len) {
chr = str[k];
if (allowed.indexOf(chr) != -1) {
S = chr;
} else {
ord = str.charCodeAt(k);
if (ord < 256) {
S = '%' + ("00" + ord.toString(16)).toUpperCase().slice(-2);
} else {
S = '%u' + ("0000" + ord.toString(16)).toUpperCase().slice(-4);
}
}
R += S;
k++;
}
return R;
};
})(typeof window == 'undefined' ? global : window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment