Is it possible to base 36 encode with JavaScript / jQuery?

后端 未结 4 2039
臣服心动
臣服心动 2021-01-31 18:00

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

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 18:34

    For anyone looking for how to encode a string in base36 (since this question, How do i convert string to base36 in javascript , is redirected here) -

    Here's what I came up with.

    /* encode / decode strings to / from base36 
    
       based on: http://snipplr.com/view/12653/
    */
    
    var base36 = {
        encode: function (str) {
            return Array.prototype.map.call(str, function (c) {
                return c.charCodeAt(0).toString(36);
            }).join("");
        },
        decode: function (str) {
            //assumes one character base36 strings have been zero padded by encodeAscii
            var chunked = [];
            for (var i = 0; i < str.length; i = i + 2) {
                chunked[i] = String.fromCharCode(parseInt(str[i] + str[i + 1], 36));
            }
            return chunked.join("");
        },
        encodeAscii: function (str) {
            return Array.prototype.map.call(str, function (c) {
                var b36 = base36.encode(c, "");
                if (b36.length === 1) {
                    b36 = "0" + b36;
                }
                return b36;
            }).join("")
        },
        decodeAscii: function (str) {
            //ignores special characters/seperators if they're included
            return str.replace(/[a-z0-9]{2}/gi, function (s) {
                return base36.decode(s);
            })
        }
    };
    
    var foo = "a-Az-Z 0-9 !@#$%^&*()-_=+[{]};:',<.>/?`~";
    var bar = base36.encodeAscii(foo);
    
    console.log(foo);
    console.log(base36.decode(bar));
    
    console.log('');
    
    var bar = "==/" + bar + "\\==";
    console.log(bar)
    console.log(base36.decodeAscii(bar));
    
    
    //doesn't work
    console.log('');
    var myString = "some string";
    var myNum = parseInt(myString, 36);
    console.log(myNum.toString(36))
    
    myString = "FooBarW000t";
    myNum = parseInt(myString, 36);
    console.log(myNum.toString(36))
    
    myString = "aAzZ09!@#$%^&*()-_=+[{]};:',<.>/?`~";
    myNum = parseInt(myString, 36);
    console.log(myNum.toString(36))
    
    /* 
    Outputs:
    
    a-Az-Z 0-9 !@#$%^&*()-_=+[{]};:',<.>/?`~
    a-Az-Z 0-9 !@#$%^&*()-_=+[{]};:',<.>/?`~
    
    ==/2p191t3e192i0w1c191l0w0x1s0z10112m12161415192n1p172j3f2l3h1n1m13181o1a1q1b1r2o3i\==
    ==/a-Az-Z 0-9 !@#$%^&*()-_=+[{]};:',<.>/?`~\==
    
    some
    foobarw000w
    aazz09
    */
    

提交回复
热议问题