且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

绝对和相对URl的javascript正则表达式

更新时间:2023-02-26 12:27:24

快速答案,修改了Arun的答案以接受"/page","/page/subpage","page/subpage"

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

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

但是实际上,从来没有说过用RegExp验证url.很多边缘情况,例如'./page'、'../page'等.

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

仔细分析您的需求,写下主要的测试用例,编写一个RegExp将它们全部通过.并注意性能.

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