How to check if a string is a valid IP address in JavaScript?

May 8, 2021 - 2 min read

To check if a string is a valid IP address (IPv4) in JavaScript, we can use a regex expression to match for the allowed number range in each of the four decimal address sections.

TL;DR

// Regular expression to check if string is a IP address
const regexExp = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/gi;

// String with IP address
const str = "192.168.5.68";

regexExp.test(str); // true

This is the regex expression for matching almost all the test cases for a valid IP address in JavaScript.

// Regular expression to check if string is a IP address
const regexExp = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/gi;

Now let's write a string with IP address like this,

// Regular expression to check if string is a IP address
const regexExp = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/gi;

// String with IP address
const str = "192.168.5.68";

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 a IP address
const regexExp = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/gi;

// String with IP address
const str = "192.168.5.68";

regexExp.test(str); // true
  • The test() method will accept a string type as an argument to test for a match.
  • The method will return boolean true if there is a match using the regular expression and false if 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 IP */
function checkIfValidIP(str) {
  // Regular expression to check if string is a IP address
  const regexExp = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/gi;

  return regexExp.test(str);
}

// Use the function
checkIfValidIP("192.168.5.68"); // true
checkIfValidIP("654.23.1.2"); // false

That's all! 😃

Feel free to share if you found this useful 😃.