使用包hashids,我可以从数字
获取哈希(并编码y解码)var Hashids = require("hashids"),
hashids = new Hashids("this is my salt", 8);
var id = hashids.encode(1);
存在一些类似的包来从字符串获取哈希? (带编码/解码)
答案 0 :(得分:25)
var Hashids = require("hashids");
var hashids = new Hashids("this is my salt");
var hex = Buffer('Hello World').toString('hex');
console.log (hex); // '48656c6c6f20576f726c64'
var encoded = hashids.encodeHex(hex);
console.log (encoded); // 'rZ4pPgYxegCarB3eXbg'
var decodedHex = hashids.decodeHex('rZ4pPgYxegCarB3eXbg');
console.log (decodedHex); // '48656c6c6f20576f726c64'
var string = Buffer('48656c6c6f20576f726c64', 'hex').toString('utf8');
console.log (string); // 'Hello World'
答案 1 :(得分:0)
在没有 Node 的 Buffer.from 的情况下获取十六进制(与 hashids.decodeHex 一起使用)
const toHex = (str: string): string => str.split("")
.reduce((hex, c) => hex += c.charCodeAt(0).toString(16).padStart(2, "0"), "")
const toUTF8 = (num: string): string =>
num.match(/.{1,2}/g)
.reduce((acc, char) => acc + String.fromCharCode(parseInt(char, 16)),"");