2

Is there any regex which will validate both an absolute URL and relateve URl for Javascript.

I do have following Regex which works fairly well for absolute URL except the part where it is making the HTTP part mandatory. I want it optional.

Here is Regex:

/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/;

thanks

1
  • A relative URL can be basically anything, so you'd have a tough time validating that Commented Feb 6, 2013 at 3:24

4 Answers 4

4

Try

/((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/;

It makes the (http|ftp|https):\/\/ (http://) portion optional

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it did make the HTTp part optional but still does not accept the relate path so it does acceprt www.google.com but it does not accept \page
1

The following should work:

/^(https?:\/\/|\/)\w+\.[^\s]+$|^\/[^\s]*$/

example

Comments

0

This one accepts things like:

http://example.com
https://example.com.com
/mypage
/my/page/

But not things like

httpa://example.com
my/page/
www

The regexp is:

/(^(https?:\/\/|\/)(?:www\.|(?!www))?[^\s])/

1 Comment

Your regex only matches the first character after https:// or http:// or /.
-1

quick answer, modified Arun's answer to accept '/page', '/page/subpage', 'page/subpage'

/(\/?[\w-]+)(\/[\w-]+)*\/?|(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?)/gi

but in actually, validate the url with RegExp is never esay. lots of edge case, like './page', '../page' etc.

analyse your requirement carefully, write down the major test cases, write a RegExp pass them all. and be careful with performance.

6 Comments

For some reason javascript editor does not recognize this string as valid Regex.
whoops, I only posted the text part. should add / on each side. already updated the answer.
I actually did replace this new one with the old one and the problem here is that now it takes anything. It would also accept plain text as a valid URL :((
because I think "plain text" is also a valid relative url. example: <a href="page_on_same_path"> or <a href="sub/page_on_sub_path">
This regex will match a single word character as well. Not exactly useful for validating relatively urls. Arun's solution below does not have the same issue.
|

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.