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.

3
  • 1
    Please post your regex which you got now. Commented Jun 9, 2014 at 12:51
  • 1
    So make the first part optional... Commented Jun 9, 2014 at 12:53
  • @Xatenev just updated it. Commented Jun 9, 2014 at 12:53

2 Answers 2

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;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Uncaught SyntaxError: Invalid regular expression: /(?:https?://|www.)+[a-z0-9-.]+.[a-z]{2,5}(?:(?:/|#|?)[^s]*)?/: Nothing to repeat
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.