如何检查字符串是否用javascript编码为base32

时间:2018-12-03 19:47:41

标签: javascript validation base32

我需要检查geohash字符串是否有效,所以我需要检查它是否为base32。

2 个答案:

答案 0 :(得分:1)

Base32使用AZ和2-7进行编码,并添加填充字符=以获取8个字符的倍数,因此您可以创建一个正则表达式来查看候选字符串是否匹配。

使用regex.exec匹配的字符串将返回匹配信息,不匹配的字符串将返回null,因此您可以使用if来测试匹配是真还是假

Base32编码的长度也必须始终是8的倍数,并用足够的=字符进行填充;您可以使用mod 8-
检查长度是否正确 if (str.length % 8 === 0) { /* then ok */ }

// A-Z and 2-7 repeated, with optional `=` at the end
let b32_regex = /^[A-Z2-7]+=*$/;

var b32_yes = 'AJU3JX7ZIA54EZQ=';
var b32_no  = 'klajcii298slja018alksdjl';
    
if (b32_yes.length % 8 === 0 &&
    b32_regex.exec(b32_yes)) {
    console.log("this one is base32");
}
else {
    console.log("this one is NOT base32");
}
    
if (b32_no % 8 === 0 &&
    b32_regex.exec(b32_no)) {
    console.log("this one is base32");
}
else {
    console.log("this one is NOT base32");
}

答案 1 :(得分:0)

function isBase32(input) {
    const regex = /^([A-Z2-7=]{8})+$/
    return regex.test(input)
}

console.log(isBase32('ABCDE23=')) //true
console.log(isBase32('aBCDE23=')) //false

console.log(isBase32('')) //false
console.log(isBase32()) //false
console.log(isBase32(null)) //false

console.log(isBase32('ABCDE567ABCDE2==')) //true
console.log(isBase32('NFGH@#$aBCDE23==')) //false

相关问题