To check if a string is a valid MD5 hash in JavaScript, we can use a regex expression to match for the 32 consecutive hexadecimal digits which are characters from a-f and numbers from 0-9.
TL;DR
// Regular expression to check if string is a MD5 hash
const regexExp = /^[a-f0-9]{32}$/gi;
// String with MD5 hash
const str = "e10adc3949ba59abbe56e057f20f883e";
regexExp.test(str); // true
This is the regex expression for matching almost all the test cases for a valid MD5 hash in JavaScript.
// Regular expression to check if string is a MD5 hash
const regexExp = /^[a-f0-9]{32}$/gi;
This will match all the 32 hexadecimal digits which have characters in the range from a till f and numbers from 0 till 9.
Now let's write a string with MD5 hash like this,
// Regular expression to check if string is a MD5 hash
const regexExp = /^[a-f0-9]{32}$/gi;
// String with MD5 hash
const str = "e10adc3949ba59abbe56e057f20f883e";
Now to test the string, we can use the test() method available in the regular expression we defined. It can be done like this,
// Regular expression to check if string is an MD5 hash
const regexExp = /^[a-f0-9]{32}$/gi;
// String with MD5 hash
const str = "e10adc3949ba59abbe56e057f20f883e";
regexExp.test(str); // true
- The
test()method will accept astringtype as an argument to test for a match. - The method will return boolean
trueif there is a match using the regular expression andfalseif not.
See the above example live in JSBin.
If you want this as a utility function which you can reuse, here it is,
/* Check if string is a valid MD5 Hash */
function checkIfValidMD5Hash(str) {
// Regular expression to check if string is a MD5 hash
const regexExp = /^[a-f0-9]{32}$/gi;
return regexExp.test(str);
}
// Use the function
checkIfValidMD5Hash("e10adc3949ba59abbe56e057f20f883e"); // true
checkIfValidMD5Hash("hello98123!"); // false
That's all! 😃