21

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.

8 Answers 8

58

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");

2
  • Hi @MarkRedman, the resource on snippets.dzone that you have linked to seems to have been moved ( I get a 410 Gone error message). Is there an updated version of it? Thanks! Jan 26, 2016 at 1:03
  • Take note that s must be in lowercase.
    – Joyce
    Mar 19, 2018 at 7:55
12
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')

6
  • This was the best one I found so far. The only thing, it returns true to isURL("http").
    – Anoyz
    Jan 26, 2014 at 13:26
  • 2
    very nice. 'https|http|ftp...' can written shorter => 'https?|ftp...'
    – algorhythm
    Nov 4, 2014 at 12:25
  • Improved version to match even 'localhost': add '|localhost' after + "[a-z]{2,6})" // first level domain- .com or .museum inside the bracket => + "[a-z]{2,6}|localhost)" // first level domain- .com or .museum
    – algorhythm
    Nov 4, 2014 at 12:30
  • IsURL('11/01/2020') --> true
    – egurb
    Jun 11, 2020 at 12:45
  • 1
    it is not accurate any string let say console.log(IsURL("rama")); it returns true. Dec 8, 2020 at 9:31
9

try something like this:

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

One for the future using the URL constructor and a basic try catch statement, it is supported in most modern browsers. Obviously no IE support...

const isUrl = (str) => {
  try {
    new URL(str);
    return true;
  } catch () {
    return false;  
  }
}

If the URL is valid it will get parsed by the constructor and return true.

If the string is not a valid URL the constructor will chuck a syntax error that will get caught and return false.

1
  • 1
    Note that this will technically pass as valid with the URL constructor: http://www.
    – tdc
    Jan 23, 2018 at 23:32
4

Try this code. This expression is more complete and takes into account IP address:

function checkUrl(s) {
     var regexp = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/
     return regexp.test(s); }
1

You can use a regular expression for checking the string

^s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#]+$  

Regular Expressions and Javascript

1

Had the same task, but all of regex that I found online to check validity of a URL were failed in some test cases.

Here is the regex that worked everything:

/^(http:\/\/www\.|https:\/\/www\.|www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?/

However, If the URL was like: google.com It accepted it as valid (which in my specific case, was considered as invalid)

It worked the best I had found. Worked like a charm!

0

When given the option, I prefer the simplest solution.

Use _.startsWith(string, 'http') if:

  • You don't mind if URL is invalid
  • You're sure the URL being checked will always start with 'http'
  • You don't expect the string to be another value that might start also with 'http'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.