In this article, you’ll learn how to check if a string is a valid SHA256 hash or Not in javascript. We used the regex expression to check if a string is a valid SHA256 hash in JavaScript. By using this regex expression, we match for the 64 consecutive hexadecimal digits which are characters from a-f and numbers from 0-9.
This is the regex expression, we used for matching almost all the test cases for a valid SHA256 hash in JavaScript.
// Regular expression to check if string is a SHA256 hash
const regexExp = /^[a-f0-9]{64}$/gi;
This regex expression will match all the 64 hexadecimal digits which have characters in the range from a till f and numbers from 0 till 9.
In this example, we used the regex expression test()
method to test if the string is a valid SHA256 hash is valid or not. It can be done like this,
// Regular expression to check if string is a SHA256 hash
const regexExp = /^[a-f0-9]{64}$/gi;
// String with SHA256 hash
const str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
console.log(regexExp.test(str)); // true
The test()
method will accept a string type as an argument to test for a matching regex expression. This method will return a boolean true
if there is a match using the regex expression and if there is no match then it will return false
.
If you want this as a utility function which you can reuse, here it is,
/* Check if string is a valid SHA256 Hash */
function checkIfValidSHA256(str) {
// Regular expression to check if string is a SHA256 hash
const regexExp = /^[a-f0-9]{64}$/gi;
return regexExp.test(str);
}
// Use the function
console.log(checkIfValidSHA256(
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
)); // true
console.log(checkIfValidSHA256("tutorialsrack!")); // false
I hope this article will help you to understand how to check if a string is a valid SHA256 hash or Not in javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments