Check if a JavaScript string is a URL

前端 未结 30 2917
野趣味
野趣味 2020-11-22 15:41

Is there a way in JavaScript to check if a string is a URL?

RegExes are excluded because the URL is most likely written like stackoverflow; that is to s

30条回答
  •  失恋的感觉
    2020-11-22 16:17

    One function that I have been using to validate a URL "string" is:

    var matcher = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/;
    
    function isUrl(string){
      return matcher.test(string);
    }
    

    This function will return a boolean whether the string is a URL.

    Examples:

    isUrl("https://google.com");     // true
    isUrl("http://google.com");      // true
    isUrl("http://google.de");       // true
    isUrl("//google.de");            // true
    isUrl("google.de");              // false
    isUrl("http://google.com");      // true
    isUrl("http://localhost");       // true
    isUrl("https://sdfasd");         // false
    

提交回复
热议问题