JavaScript Base62 Sample Code

Discover JavaScript code samples for encoding and decoding data in Base62 format, suitable for web applications.

const BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

function encode(input) {
    if (input.length === 0) {
        return "";
    }

    let value = BigInt("0x" + Buffer.from(input, 'utf8').toString('hex'));
    let result = "";

    while (value > 0) {
        let divmod = value % 62n;
        result = BASE62[divmod] + result;
        value = value / 62n;
    }

    for (let i = 0; i < input.length; i++) {
        if (input.charCodeAt(i) === 0) {
            result = BASE62[0] + result;
        } else {
            break;
        }
    }

    return result;
}

function decode(input) {
    if (input.length === 0) {
        return "";
    }

    let value = BigInt(0);
    for (let i = 0; i < input.length; i++) {
        value = value * 62n + BigInt(BASE62.indexOf(input[i]));
    }

    let hex = value.toString(16);
    if (hex.length % 2) {
        hex = '0' + hex;
    }

    let bytes = Buffer.from(hex, 'hex');
    let leadingZeroes = 0;
    for (let i = 0; i < input.length; i++) {
        if (input[i] === BASE62[0]) {
            leadingZeroes++;
        } else {
            break;
        }
    }

    let result = Buffer.concat([Buffer.alloc(leadingZeroes), bytes]);
    return result.toString('utf8');
}

// Usage
const input = "hfdsdsfs";
const encoded = encode(input);
console.log("Encoded:", encoded);

const decoded = decode(encoded);
console.log("Decoded:", decoded);

Base62 Sample Code