base36 Encode/Decode [JS 1.8]


/ Published in: JavaScript
Save to your folder(s)

base36 Encode/Decode Strings
====================

*Requires JavaScript 1.8 or higher*

Syntax:

`base36[.ascii].encode(str[, separator]):String`

`base36[.ascii].decode(str[, separator]):String`

Default character separator is ZERO WIDTH SPACE U+200B

Examples:

base36.encode("foobar", "-") == "2u-33-33-2q-2p-36"
base36.decode("2u-33-33-2q-2p-36", "-") == "foobar"


Copy this code and paste it in your HTML
  1. if (delete base36)
  2. const base36 = { // U+200B is a zero-width space
  3. encode: function(str, separator)
  4. Array.map(""+(str||""), function(c) c.charCodeAt(0).toString(36)).join(separator||"\u200b"),
  5. decode: function(str, separator)
  6. (""+(str||"")).split(separator||"\u200b").map(function(s) String.fromCharCode(parseInt(s, 36))).join(""),
  7. ascii: {
  8. encode: function(str)
  9. Array.map(""+(str||""), function(c) {
  10. var b36 = base36.encode(c, "");
  11. if (b36.length === 1)
  12. b36 = "0" + b36;
  13. return b36;
  14. }).join(""),
  15.  
  16. decode: function(str)
  17. (""+(str||"")).replace(/[a-z0-9]{2}/gi, function(s) base36.decode(s))
  18. }
  19. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.