Here’s the regular expression to check for a valid IP:
function isValidIP(str) {
return /^(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])(\.(?!$)|$)){4}$/.test(str);
}
Here’s the breakdown:
^
asserts the start of the string.(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])(\.(?!$)|$)){4}
matches the IP address pattern for four octets.
([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])
matches a single octet value. Breaking it down further:
[1-9]?\d
matches a single digit or a two-digit number that does not start with zero (range 1-99).1\d\d
matches any three-digit number starting with ‘1’ (range 100-199).2[0-4]\d
matches any three-digit number starting with ‘2’ and followed by a digit from 0 to 4 (range 200-249).25[0-5]
matches any three-digit number starting with ’25’ and followed by a digit from 0 to 5 (range 250-255).(\.(?!$)|$)
matches the delimiter dot ‘.’ between octets or the end of the string:
\.(?!$)
matches a dot ‘.’ that is not followed by the end of the string (negative lookahead).$
matches the end of the string.{4}
specifies that the pattern should occur exactly four times (matching four octets).$
asserts the end of the string.The regular expression achieves the same as the following code which is much longer:
function isValidIP(str) {
// check if number has four octets (less than four values)
let array = str.split('.');
let length = array.length;
if (length != 4) {
return false;
}
// create for loop
for (let i = 0; i < length; i++){
// check if numbers have leading zeros only if they're greater two digits
if(array[i].length >= 2) {
if(array[i].charAt(0) === '0' || array[i].charAt(0) === ' ' || array[i].endsWith(' ') || isNaN(array[i]) || array[i].includes('e') || array[i].includes('\n') || array[i].charAt(1) === ' ' || array[i] < 0) {
return false;
}
}
// check if length is zero
if(array[i].length === 0) {
return false;
}
// check if values are not numbers
if(isNaN(array[i])) {
return false;
}
// check if numbers are greater than 255
if(array[i] > 255) {
return false;
}
}
return true;
}
Have any questions or comments? Write them below!