Check if a JavaScript string is a URL

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

    I think using the native URL API is better than a complex regex patterns as @pavlo suggested. It has some drawbacks though which we can fix by some extra code. This approach fails for the following valid url.

    //cdn.google.com/script.js
    

    We can add the missing protocol beforehand to avoid that. It also fails to detect following invalid url.

    http://w
    http://..
    

    So why check the whole url? we can just check the domain. I borrowed the regex to verify domain from here.

    function isValidUrl(string) {
        if (string && string.length > 1 && string.slice(0, 2) == '//') {
            string = 'http:' + string; //dummy protocol so that URL works
        }
        try {
            var url = new URL(string);
            return url.hostname && url.hostname.match(/^([a-z0-9])(([a-z0-9-]{1,61})?[a-z0-9]{1})?(\.[a-z0-9](([a-z0-9-]{1,61})?[a-z0-9]{1})?)?(\.[a-zA-Z]{2,4})+$/) ? true : false;
        } catch (_) {
            return false;
        }
    }
    

    The hostname attribute is empty string for javascript:void(0), so it works for that too, and you can also add IP address verifier too. I'd like to stick to native API's most, and hope it starts to support everything in near future.

提交回复
热议问题