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

    2 answers 2

    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)); 

    • @vp_arth, [01]?\d?\d - the first 0 is intentionally allowed. On the other hand, 0000.6.7.8 is not expected anymore - yes, weird :) - Qwertiy
    • In principle, nothing bad, I think at 00.00.00.00 no) Well, okay) - vp_arth
    • @ WiktorStribiżew, what is the point of changing the answer? - Qwertiy
    • one
      @Qwertiy Firstly, for some reason it seemed to me that this is my answer :) Sorry. Secondly, I wanted to specifically indicate what needs to be added so that future visitors would not have any questions about how such problems are solved. - Wiktor Stribiżew
    • @ WiktorStribiżew, in general, if you simply add to the beginning and end, it may turn out wrong. Example: 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)));