Check if a JavaScript string is a URL

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

    2020 Update. To expand on both excellent answerd from @iamnewton and @Fernando Chavez Herrera I've started to see @ being used in the path of URLs.

    So the updated regex is:

    RegExp('(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+@]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$', 'i');
    

    If you want to allow it in the query string and hash, use:

    RegExp('(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+@]*)*(\\?[;&a-z\\d%_.~+=-@]*)?(\\#[-a-z\\d_@]*)?$', 'i');
    

    That being said, I'm not sure if there's a whitepaper rule disallowing @ in the query string or hash.

    0 讨论(0)
  • 2020-11-22 16:15

    Here's just a very simple check to make sure there's a valid protocol, and the domain extension must be two or more characters.

    is_valid_url = ( $url ) => {
    
        let $url_object = null;
    
        try {
            $url_object = new URL( $url );
        } catch ( $error ) {
            return false;
        }
    
        const $protocol = $url_object.protocol;
        const $protocol_position = $url.lastIndexOf( $protocol );
        const $domain_extension_position = $url.lastIndexOf( '.' );
    
        return (
            $protocol_position === 0 &&
            [ 'http:', 'https:' ].indexOf( $protocol ) !== - 1 &&
            $domain_extension_position > 2 && $url.length - $domain_extension_position > 2
        );
    
    };
    
    0 讨论(0)
  • 2020-11-22 16:16

    Rely on a library: https://www.npmjs.com/package/valid-url

    import { isWebUri } from 'valid-url';
    // ...
    if (!isWebUri(url)) {
        return "Not a valid url.";
    }
    
    0 讨论(0)
  • 2020-11-22 16:16

    this working with me

    function isURL(str) {
      var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
      var pattern = new RegExp(regex); 
    return pattern.test(str);
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 16:19

    A related question with an answer:

    Javascript regex URL matching

    Or this Regexp from Devshed:

    function validURL(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)
提交回复
热议问题