Check if a JavaScript string is a URL

前端 未结 30 2869
野趣味
野趣味 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:";
    }
    
    0 讨论(0)
  • 2020-11-22 16:19

    I change the function to Match + make a change here with the slashes and its work: (http:// and https) both

    function isValidUrl(userInput) {
        var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
        if(res == null)
           return false;
        else
           return true;
    }
    
    0 讨论(0)
  • 2020-11-22 16:20
    function isURL(str) {
      var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+ // domain name
      '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
      '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
      '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
      '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
      return pattern.test(str);
    }
    
    0 讨论(0)
  • 2020-11-22 16:22

    Improvement on the accepted answer...

    • Check for ftp/ftps as protocol
    • Has double escaping for backslashes (\\)
    • Ensures that domains have a dot and an extension (.com .io .xyz)
    • Allows full colon (:) in the path e.g. http://thingiverse.com/download:1894343
    • Allows ampersand (&) in path e.g http://en.wikipedia.org/wiki/Procter_&_Gamble
    • Allows @ symbol in path e.g. https://medium.com/@techytimo

      isURL(str) {
        var pattern = new RegExp('^((ft|htt)ps?:\\/\\/)?'+ // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name and extension
        '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
        '(\\:\\d+)?'+ // port
        '(\\/[-a-z\\d%@_.~+&:]*)*'+ // path
        '(\\?[;&a-z\\d%@_.,~+&:=-]*)?'+ // query string
        '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
        return pattern.test(str);
      }
      
    0 讨论(0)
  • 2020-11-22 16:22

    You can use the URL native API:

      const isUrl = string => {
          try { return Boolean(new URL(string)); }
          catch(e){ return false; }
      }
    
    0 讨论(0)
  • 2020-11-22 16:22

    If you can change the input type, I think this solution would be much easier:

    You can simple use type="url" in your input and the check it with checkValidity() in js

    E.g:

    your.html

    <input id="foo" type="url">
    

    your.js

    // The selector is JQuery, but the function is plain JS
    $("#foo").on("keyup", function() {
        if (this.checkValidity()) {
            // The url is valid
        } else {
            // The url is invalid
        }
    });
    
    0 讨论(0)
提交回复
热议问题