Skip to content

Commit

Permalink
Refactor: Simplified code by using \b in IPv4 regular expression
Browse files Browse the repository at this point in the history
  • Loading branch information
UnKnoWn-Consortium authored May 16, 2022
1 parent cfcf911 commit 8447a40
Showing 1 changed file with 2 additions and 6 deletions.
8 changes: 2 additions & 6 deletions src/lib/isIP.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import assertString from './util/assertString';
* * */
const IPv4SegmentFormat = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
const IPv4AddressFormat = `(${IPv4SegmentFormat}[.]){3}${IPv4SegmentFormat}`;
const IPv4AddressRegExp = new RegExp(`^${IPv4AddressFormat}$`);
const IPv4AddressRegExp = new RegExp(`^\b${IPv4AddressFormat}\b$`);

const IPv6SegmentFormat = '(?:[0-9a-fA-F]{1,4})';
const IPv6AddressRegExp = new RegExp('^(' +
Expand All @@ -51,11 +51,7 @@ export default function isIP(str, version = '') {
return isIP(str, 4) || isIP(str, 6);
}
if (version === '4') {
if (!IPv4AddressRegExp.test(str)) {
return false;
}
const parts = str.split('.').sort((a, b) => a - b);
return parts[3] <= 255;
return !!IPv4AddressRegExp.test(str);
}
if (version === '6') {
return !!IPv6AddressRegExp.test(str);
Expand Down

0 comments on commit 8447a40

Please sign in to comment.