Last active
December 18, 2015 08:49
-
-
Save m1el/5757447 to your computer and use it in GitHub Desktop.
#query #cp1251 #encoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// License = MIT | |
var encodeCp1251 = (function(){ | |
var alphabet = 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя'; | |
function replacefn(c) { | |
var i = alphabet.indexOf(c); | |
if (i > -1) { | |
return '%' + (i + 0xc0).toString(16); | |
} | |
if (c.charCodeAt(0) < 128) { | |
return escape(c); | |
} else { | |
return '.'; // we don't encode non-russian and ascii characters | |
} | |
}; | |
return function(str) { | |
return ('' + str).replace(/[^a-z0-9_.-]/ig, replacefn); | |
} | |
})(); | |
var objTo1251Query = (function(encoder){ | |
function appendVal(result, path, obj) { | |
var i, keys; | |
if (obj && Object.prototype.toString.call(obj) === '[object Array]') { | |
for (i = 0; i < obj.length; i++) { | |
appendVal(result, path + '[' + i + ']', obj[i], encoder); | |
} | |
} else if (obj && typeof obj === 'object') { | |
keys = Object.keys(obj); | |
for (i = 0; i < keys.length; i++) { | |
appendVal(result, (path.length ? path + '[' + keys[i] + ']' : keys[i]), obj[keys[i]], encoder); | |
} | |
} else { | |
result.push(encoder(path) + '=' + encoder(obj)); | |
} | |
return result; | |
} | |
return function(obj) { | |
return appendVal([], '', obj).join('&'); | |
}; | |
})(encodeCp1251); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment