-1

I'm trying to check strings to see it they are a valid IP address:

export function checkIpIsValid(ip) {                                          
    const regex = new RegExp("^([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}$")     
    return regex.test(ip);                                                    
}   

But this test is failing because it return true:

expect(checkIpIsValid("1.1.1.1")).toBe(true);            
expect(checkIpIsValid("152.154.22.35")).toBe(true);      
expect(checkIpIsValid("552.154.22.35")).toBe(false);

// These three are fine
// But the one below is not, it doesn't contain 4 parts so it should return false. Instead, it is returning true.      

expect(checkIpIsValid("154.22.35")).toBe(false);     


// Expected value to be (using ===):
//   false
// Received:
//   true

The thing is, when I check it on https://regex101.com/ it works fine on that case...

Enuff
  • 457
  • 5
  • 21
  • No, that does not match. The regex is not correct for IPs, but it does not match the input. Compare. https://regex101.com/r/t4Ooc8/1 – Tomalak Dec 03 '17 at 10:32
  • Can you describe what you want to match? – Prashant Dec 03 '17 at 10:38
  • @tomalak Yep, in regex101.com that appears to be correct, but when you run in on javascript, i'm getting a match with the exact same regular expression. – Enuff Dec 03 '17 at 10:51

2 Answers2

4

Don't use new RegExp(). This expects a string input, but your expression is not escaped for string. You just enclosed it in double quotes, that doesn't work.

Either use a regex literal:

function checkIpIsValid(ip) {
    const regex = /^([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}$/;    
    return regex.test(ip);                                                    
}

or escape he expression properly:

function checkIpIsValid(ip) {
    const regex = new RegExp("^([1-2]?[0-9]{1,2}\\.){3}[1-2]?[0-9]{1,2}$");    
    return regex.test(ip);                                                    
}

JS has regex literals exactly because that avoids the need for double-escaping. Use new RegExp() only for dynamically built expressions, not for fixed ones.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
1
function checkIpIsValid(ip) {
    return /^(?:\d{1,3}\.){3}\d{1,3}$/.test(ip);
}

checkIpIsValid('123.12.12'); // returns false
checkIpIsValid('123.12.12.12'); // returns true
Prashant
  • 7,340
  • 2
  • 25
  • 24
  • Humm, the thing is that one will match my third test case: `552.154.22.35` and it shouldn't – Enuff Dec 03 '17 at 10:57