Check if a JavaScript string is a URL

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

    Rather than using a regular expression, I would recommend making use of an anchor element.

    when you set the href property of an anchor, various other properties are set.

    var parser = document.createElement('a');
    parser.href = "http://example.com:3000/pathname/?search=test#hash";
    
    parser.protocol; // => "http:"
    parser.hostname; // => "example.com"
    parser.port;     // => "3000"
    parser.pathname; // => "/pathname/"
    parser.search;   // => "?search=test"
    parser.hash;     // => "#hash"
    parser.host;     // => "example.com:3000"
    

    source

    However, if the value href is bound to is not a valid url, then the value of those auxiliary properties will be the empty string.

    Edit: as pointed out in the comments: if an invalid url is used, the properties of the current URL may be substituted.

    So, as long as you're not passing in the URL of the current page, you can do something like:

    function isValidURL(str) {
       var a  = document.createElement('a');
       a.href = str;
       return (a.host && a.host != window.location.host);
    }
    

提交回复
热议问题