Как проверить, если строка в кодировке base32 в javascript
Мне нужно проверить, допустима ли строка геохеша, поэтому мне нужно проверить, является ли она base32 или нет.
3 ответа
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");
}
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
//Я собрал эту маленькую кнопку HTML и js, чтобы с ней возиться.
<!DOCTYPE html>
<html>
<head>
<title>Base32/Base64 Checker</title>
</head>
<body>
<h1>Base32/Base64 Checker</h1>
<label for="input">Enter a string:</label>
<input type="text" id="input" name="input"><br><br>
<button onclick="check()">Check</button>
<p id="result"></p>
<script>
function check() {
var input = document.getElementById("input").value;
var isBase32 = /^[A-Z2-7]+=*$/.test(input);
var isBase64 = /^[A-Za-z0-9+/]+=*$/i.test(input);
var result;
if (isBase32) {
result = "The input is Base32 encoded.";
} else if (isBase64) {
result = "The input is Base64 encoded.";
} else {
result = "Neither Base32 nor Base64 !.";
}
document.getElementById("result").innerHTML = result;
}
</script>
</body>
</html>