How to detect whether a string is in URL format using javascript?

前端 未结 7 1865
轻奢々
轻奢々 2020-12-18 19:52

I think the question title seems to explain eveything. I want to detect whether a string is in URL format or not using javascript.

Any help appreciated.

7条回答
  •  渐次进展
    2020-12-18 20:36

    function IsURL(url) {
    
        var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
            + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
            + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
            + "|" // 允许IP和DOMAIN(域名)
            + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
            + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
            + "[a-z]{2,6})" // first level domain- .com or .museum
            + "(:[0-9]{1,4})?" // 端口- :80
            + "((/?)|" // a slash isn't required if there is no file name
            + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
         var re=new RegExp(strRegex);
         return re.test(url);
     }
    

    Regular expression visualization

    Debuggex Demo (Improved version which matches also 'localhost')

提交回复
热议问题