Check if a JavaScript string is a URL

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

    Here is yet another method.

    var elm;
    function isValidURL(u){
      if(!elm){
        elm = document.createElement('input');
        elm.setAttribute('type', 'url');
      }
      elm.value = u;
      return elm.validity.valid;
    }
    
    console.log(isValidURL('http://www.google.com/'));
    console.log(isValidURL('//google.com'));
    console.log(isValidURL('google.com'));
    console.log(isValidURL('localhost:8000'));

提交回复
热议问题