Skip to content

Instantly share code, notes, and snippets.

@karadza3a
Forked from alkaruno/Base64.js
Last active February 24, 2019 23:59
Show Gist options
  • Save karadza3a/73cb954ce79ac1936935d68a5e666f05 to your computer and use it in GitHub Desktop.
Save karadza3a/73cb954ce79ac1936935d68a5e666f05 to your computer and use it in GitHub Desktop.
Base62 encode & decode (alphanumeric only) in JavaScript
var Base62 = (function () {
var ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var Base62 = function () {};
var _encode = function (value) {
if (typeof(value) !== 'number') {
throw 'Value is not number!';
}
var result = '', mod;
do {
mod = value % 62;
result = ALPHA.charAt(mod) + result;
value = Math.floor(value / 62);
} while(value > 0);
return result;
};
var _decode = function (value) {
var result = 0;
for (var i = 0, len = value.length; i < len; i++) {
result *= 62;
result += ALPHA.indexOf(value[i]);
}
return result;
};
Base62.prototype = {
constructor: Base62,
encode: _encode,
decode: _decode
};
return Base62;
})();
@karadza3a
Copy link
Author

var base62 = new Base62();

base62.encode(3270397159014518); // > "O8pK4ZIns"

base62.decode('O8pK4ZIns'); // > 3270397159014518

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment