0

I have a string to validate if it is a valid url or not. I have googled it, I could only found the solution if url contains http or https

I want to make the url as valid even if it does not contain http infront of its domain name example -> www.google.com

These are some of the urls I have tried and they did work.

http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without-the
http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links
http://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-an-url

But they validate it as true even when I give h/www.stackoverflow.com which is not a valid url also /www.stackoverflow.com validates to true

They are not the valid urls. Can anyone help me writing the regular expression. I wanted to write this regular exp on my own but I am unable to find good tutorials on regexp. I could barely write expressions such as containing a character, a litle small ones.

I believe its the area Iam little weak I want to practise some regular expressions. Any help is greatly appreciated.

Kindly help me in validating this url.

Update

 ((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)

This is the regexp Iam currently using

I kindly request you to make a js fiddle and that makes h/www.stackoverflow.com to false. Sorry but none of the answers did not work.

user3205479
  • 1,443
  • 1
  • 17
  • 41

2 Answers2

0

You can use this (works on urls that starts with www.)

function ValidURL(str) {
  var pattern = new RegExp('(?:https?:\/\/|www\.)+[a-z0-9\-\.]+\.[a-z]{2,5}(?:(?:\/|#|\?)[^\s]*)?','i');
  if(!pattern.test(str)) {
    return false;
  } else {
    return true;
  }
}
Adrian B
  • 1,490
  • 1
  • 19
  • 31
  • Uncaught SyntaxError: Invalid regular expression: /(?:https?://|www.)+[a-z0-9-.]+.[a-z]{2,5}(?:(?:/|#|?)[^s]*)?/: Nothing to repeat – user3205479 Jun 09 '14 at 13:16
0

You can use an alternate method for matching URLs if they are strings.

var x;
try {
    var t = new URL( yourStringHere );
    x = true;
}
catch( e ) {
    x = false;
}
hjpotter92
  • 78,589
  • 36
  • 144
  • 183