Check if a JavaScript string is a URL

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

    There's a lot of answers already, but here's another contribution: Taken directly from the URL polyfill validity check, use an input element with type="url" to take advantage of the browser's built-in validity check:

    var inputElement = doc.createElement('input');
    inputElement.type = 'url';
    inputElement.value = url;
    
    if (!inputElement.checkValidity()) {
        throw new TypeError('Invalid URL');
    }
    

    Source

提交回复
热议问题