var value = "192.25.23.1"
// Check if value is an IP address
if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(value)) {
return true;
}
var parts = value.split(".");
if (parts.length !== 4) {
return false;
}
for (var i = 0; i < parts.length; i++) {
var part = parseInt(parts[i]);
if (isNaN(part) || part < 0 || part > 255) {
return false;
}
}
return true;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex | |
split |
Test name | Executions per second |
---|---|
regex | 6968688.0 Ops/sec |
split | 678390.6 Ops/sec |
Let's break down the benchmark test and explain what's being tested.
Benchmark Overview
The benchmark tests two approaches to validate if a given string represents an IP address:
We'll discuss each approach, its pros and cons, and other considerations.
Approach 1: Regular Expression (Regex)
The Benchmark Definition
JSON contains a regular expression that checks if the input string value
matches the IP address pattern:
if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(value)) {
return true;
}
This regular expression breaks down as follows:
^
matches the start of the string(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
matches a single octet (a value between 0 and 255)\.
matches a literal period character$
matches the end of the stringPros:
Cons:
Approach 2: String Splitting
The second approach splits the input string value
into individual octets using the .
character as a delimiter:
var parts = value.split(".");
if (parts.length !== 4) {
return false;
}
for (var i = 0; i < parts.length; i++) {
var part = parseInt(parts[i]);
if (isNaN(part) || part < 0 || part > 255) {
return false;
}
}
This approach is more straightforward than the regular expression approach.
Pros:
Cons:
Library Used
In both approaches, no external libraries are required. The regular expression pattern is a built-in JavaScript feature, while the split()
method is another native JavaScript function.
Special JS Feature/ Syntax
No special JavaScript features or syntax are used in this benchmark test.
Other Alternatives
Other alternatives to validate IP addresses include:
ip-address
(Node.js) or ipaddr
(Python).However, for a simple benchmark like this one, the built-in JavaScript functions and regular expression pattern are sufficient.