javascript Regex for Absolute AND relative URl

て烟熏妆下的殇ゞ 提交于 2019-12-11 01:37:54

问题


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:


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.




回答2:


Try

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

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




回答3:


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])/


来源:https://stackoverflow.com/questions/14720940/javascript-regex-for-absolute-and-relative-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!