我需要检查 geohash 字符串是否有效,所以我需要检查它是否是 base32。
user10576882
问问题
1971 次
2 回答
2
Base32使用 AZ 和 2-7 进行编码,并添加一个填充字符=
以获得 8 个字符的倍数,因此您可以创建一个正则表达式来查看候选字符串是否匹配。
使用regex.exec
匹配的字符串会返回匹配信息,不匹配的字符串会返回null
,所以可以使用 anif
来测试匹配是真还是假。
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");
}
于 2018-12-03T20:03:42.810 回答
1
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
于 2020-07-27T23:02:09.010 回答