Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 297
Manish Avatar asked Nov 09 '09 15:11

Manish


People also ask

How do you check if a string is a URL JavaScript?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.

How do you validate a URL?

When you create a URL input with the proper type value, url , you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate URL. This can help avoid cases in which the user mis-types their web site's address, or provides an invalid one.

Are URLs strings?

What Are URL Parameters? URL parameters (known also as “query strings” or “URL query parameters”) are elements inserted in your URLs to help you filter and organize content or track information on your website.


2 Answers

Try this-

function isUrl(s) {
   var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
   return regexp.test(s);
}

usage: if (isUrl("http://www.page.com")) alert("is correct") else alert("not correct");

like image 111
Mark Redman Avatar answered Oct 24 '22 08:10

Mark Redman


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')

like image 37
zhailulu Avatar answered Oct 24 '22 07:10

zhailulu