I\'m thinking about using the encode/decode technique here (Encoding to base 36/decoding from base 36 is simple in Ruby)
how to implement a short url like urls in twitte
The toString
method on Number
has an optional argument of radix:
(128482).toString(36);
128482..toString(36);
128482 .toString(36);
var num = 128482; num.toString(36);
Note this doesn't work, because numbers expect decimal digits after a period, not letters:
128482.toString(36); // Syntax error
Also, you can decode with JS as well:
parseInt("2r4y", 36);
EDIT:
But if I want to remove look-alike characters (1-l or 0-O) what can I do?
The easiest is to reduce the base by number of characters you're skipping, then make a translation: Note that only one of 1-l
or 0-O
is a problem, since base36 encodes only lowercase (in which case you have 1-l
, but not 0-O
) which you can make uppercase (in which case, vice versa).
(128482).toString(36).replace(/[m-y]/, x => String.fromCharCode(x.charCodeAt(0) + 1))
If you want to have a base larger than 36, you would have to have your own base-changing function, as 36 is as high as toString
supports. In that case, it is easy enough to make your own digit inventory as you want.
for working with long numbers?
Go ahead :) Note the n
suffix that turns the number into BigInt:
1000000000000000000000000000000000000000000000000000000000n.toString(36)
// => "9edwccv83mch429oxmlxupo4z1bdaiusrm29s"