6

I tried to check if url is valid or invalid. the checks of 7,8 returns wrong outputs.

alert('1: ' + learnRegExp('http://www.google-com.123.com')); // true
alert('2: ' + learnRegExp('http://www.google-com.123')); // false
alert('3: ' + learnRegExp('https://www.google-com.com')); // true
alert('4: ' + learnRegExp('http://google-com.com')); // true
alert('5: ' + learnRegExp('http://google.com')); //true
alert('6: ' + learnRegExp('google.com')); //true
alert('7: ' + learnRegExp('ww.google.com')); //false -> it returns true
alert('8: ' + learnRegExp('www.google.co.il')); //true -> it returns false
alert('9: ' + learnRegExp('http://ww.google.co.il')); //false
alert('10: ' + learnRegExp('https://ww.google.co.il')); //false

function learnRegExp(){
    return /((ftp|https?):\/\/)?(www\.)?[a-z0-9\-\.]{3,}\.[a-z]{3}$/
    .test(learnRegExp.arguments[0]);
}

please help me to solve it.

any help appreciated!

6
  • 4
    Remember that www is just a subdomain. I wouldn't bother explicitly including that in the regex. Jul 18, 2013 at 14:38
  • 1
    A lot of things can be a valid URL e.g. http://xyz.mysite.org.ru I guess the real test would be try and load it Jul 18, 2013 at 14:40
  • 1
    gist.github.com/dperini/729294
    – Mulan
    Jul 18, 2013 at 14:42
  • 4
    ww.google.com is a valid domain.
    – sp00m
    Jul 18, 2013 at 14:44
  • 2
    I would say that this question is distinct from the proposed duplicate, as ECMA and PHP do use two different flavors of Regular Expressions. Jul 18, 2013 at 14:52

2 Answers 2

8

Try this one:

 function learnRegExp(s) {    
      var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
      return regexp.test(s);    
 }
2
  • 5
    Unfortunately this runs 'true' for learnRegExp("fgsdfjgd") as well, which should be 'false'
    – patrick
    Mar 11, 2014 at 21:54
  • It's fine now, just take note that s must be in lowercase.
    – Joyce
    Mar 19, 2018 at 7:55
0

Problem with 7 is (www\.)? is allows 0 or 1 www. and [a-z0-9\-\.] allows . Since it's only ww. then (www\.)? treats it as 0 and [a-z0-9\-\.] captures the ww..

Problem with 8 is \.[a-z]{3} only allows for .com, .net, etc. It forces the string after the last . to be 3 characters long. Since it's only 2 characters, it doesn't match.

Don't try to recreate the wheel: What is the best regular expression to check if a string is a valid URL?

1
  • 2
    unfortunately the RegExp on that page is in PHP, not in JavaScript as was asked...
    – patrick
    Mar 11, 2014 at 21:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.