Check if a JavaScript string is a URL

前端 未结 30 3424
野趣味
野趣味 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:19

    You can try to use URL constructor: if it doesn't throw, the string is a valid URL:

    function isValidUrl(string) {
      try {
        new URL(string);
      } catch (_) {
        return false;  
      }
    
      return true;
    }
    

    The term 'URL' is defined in RFC 3886 (as URI); it must begin with a scheme name, and the scheme name is not limited to http/https.

    Notable examples:

    • www.google.com is not valid URL (missing scheme)
    • javascript:void(0) is valid URL, although not an HTTP one
    • http://.. is valid URL, with the host being ..; whether it resolves depends on your DNS
    • https://google..com is valid URL, same as above

    If you want to check whether a string is a valid HTTP URL:

    function isValidHttpUrl(string) {
      let url;
    
      try {
        url = new URL(string);
      } catch (_) {
        return false;  
      }
    
      return url.protocol === "http:" || url.protocol === "https:";
    }
    

提交回复
热议问题