JavaScript 代码段

数字转换

  • 十进制和16进制相互转换

    1
    2
    let hexNumber = (n).toString(16); // to hex
    let decimal = parseInt(hexNumber, 16); // to decimal
  • 16进制字符串转换为ACSII

From: Stack Overflow

1
2
3
4
5
6
7
8
9
function hex2a(data) {
let hex = data.toString();
let str = '';
for(let i = 0; i < hex.length; i += 2) {
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}

return str;
}

加密

  • sha1 加密
    1
    2
    3
    var crypto = require('crypto');
    var sha1 = crypto.createHash('sha1');
    sha1.update('str').digest('hex');

其它

  • padLeft

    1
    2
    3
    4
    5
    6
    7
    // ES6

    function padLeft(str, len) {
    let val = '0'.repeat(len - str.length) + str;

    return val;
    }
  • reverse

    1
    2
    3
    function reverse(str) {
    return str.split('').reverse().join('');
    }