How to check for IP address using regular expression in Javascript?

24-May-2023

.

Admin

How to check for IP address using regular expression in Javascript?

This tutorial will give you example of javascript regular expression to check for ip addresses. In this article, we will implement a javascript : ip address validation. it's simple example of javascript ip address validation example. we will help you to give example of how to check for ip address using regular expression in javascript.

You can use the following regular expression to check for an IP address in Javascript:

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to check for IP address using regular expression in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const ipAddressRegex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/;

</script>

</html>

This regex pattern matches any string that contains four sets of numbers separated by periods, where each set of numbers is between 0 and 255.

To use this regex to check for an IP address in Javascript, you can do the following:

Example 2:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to check for IP address using regular expression in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const ipAddress = "192.168.1.1";

if (ipAddressRegex.test(ipAddress)) {

console.log("Valid IP address");

} else {

console.log("Invalid IP address");

}

</script>

</html>

This code will output "Valid IP address" if the ipAddress variable contains a valid IP address, and "Invalid IP address" otherwise.

#JavaScript