最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript Regex for Absolute AND relative URl - Stack Overflow

programmeradmin8浏览0评论

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

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

Share Improve this question asked Feb 6, 2013 at 3:22 LostLost 13.7k36 gold badges128 silver badges210 bronze badges 1
  • A relative URL can be basically anything, so you'd have a tough time validating that – Explosion Pills Commented Feb 6, 2013 at 3:24
Add a ment  | 

4 Answers 4

Reset to default 4

Try

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

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

The following should work:

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

This one accepts things like:

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

But not things like

httpa://example.
my/page/
www

The regexp is:

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

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.

发布评论

评论列表(0)

  1. 暂无评论