Check if a JavaScript string is a URL

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

    If you can change the input type, I think this solution would be much easier:

    You can simple use type="url" in your input and the check it with checkValidity() in js

    E.g:

    your.html

    
    

    your.js

    // The selector is JQuery, but the function is plain JS
    $("#foo").on("keyup", function() {
        if (this.checkValidity()) {
            // The url is valid
        } else {
            // The url is invalid
        }
    });
    

提交回复
热议问题