var re = /((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)/; var str4 = "1300.6.7.8"; console.log(re.test(str4)); why the test gives out labor, please explain. purpose - I check IP v.4 address
var re = /((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)/; var str4 = "1300.6.7.8"; console.log(re.test(str4)); why the test gives out labor, please explain. purpose - I check IP v.4 address
You need to add ^ ( beginning of the line ) to the beginning and $ ( end of the line ) to the end of the template to check for the beginning and end of the line. Without ^ and $ is a substring.
var re = /((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)/; var str4 = "1300.6.7.8"; console.log(str4.match(re)); var re2 = /^(((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d))$/; console.log(str4.match(re2)); console.log(re2.test(str4)); [01]?\d?\d - the first 0 is intentionally allowed. On the other hand, 0000.6.7.8 is not expected anymore - yes, weird :) - Qwertiy ♦abc|xyz . - Qwertiy ♦Better to do without regular expressions:
function isIPv4(ip) { let parts = ip.split('.'); if (parts.length !== 4) return false; return parts.map(p => +p) .every(p => p >= 0 && p < 256); } [ '127.0.0.1', '1.2a.3.4', '256.0.0.0' ].forEach(ip => console.log(ip, isIPv4(ip))); Source: https://ru.stackoverflow.com/questions/743426/
All Articles