Check if a JavaScript string is a URL

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

    I am using below function to validate URL with or without http/https:

    function isValidURL(string) {
      var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
      return (res !== null)
    };
    
    var testCase1 = "http://en.wikipedia.org/wiki/Procter_&_Gamble";
    console.log(isValidURL(testCase1)); // return true
    
    var testCase2 = "http://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&docid=nIv5rk2GyP3hXM&tbnid=isiOkMe3nCtexM:&ved=0CAUQjRw&url=http%3A%2F%2Fanimalcrossing.wikia.com%2Fwiki%2FLion&ei=ygZXU_2fGKbMsQTf4YLgAQ&bvm=bv.65177938,d.aWc&psig=AFQjCNEpBfKnal9kU7Zu4n7RnEt2nerN4g&ust=1398298682009707";
    console.log(isValidURL(testCase2)); // return true
    
    var testCase3 = "https://sdfasd";
    console.log(isValidURL(testCase3)); // return false
    
    var testCase4 = "dfdsfdsfdfdsfsdfs";
    console.log(isValidURL(testCase4)); // return false
    
    var testCase5 = "magnet:?xt=urn:btih:123";
    console.log(isValidURL(testCase5)); // return false
    
    var testCase6 = "https://stackoverflow.com/";
    console.log(isValidURL(testCase6)); // return true
    
    var testCase7 = "https://w";
    console.log(isValidURL(testCase7)); // return false
    
    var testCase8 = "https://sdfasdp.ppppppppppp";
    console.log(isValidURL(testCase8)); // return false

提交回复
热议问题