Check if a JavaScript string is a URL

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

    Use validator.js

    ES6

    import isURL from 'validator/lib/isURL'
    
    isURL(string)
    

    No ES6

    var validator = require('validator');
    
    validator.isURL(string)
    

    You can also fine tune this function's behavior by passing optional options object as the second argument of isURL

    Here is the default options object:

    let options = {
        protocols: [
            'http',
            'https',
            'ftp'
        ],
        require_tld: true,
        require_protocol: false,
        require_host: true,
        require_valid_protocol: true,
        allow_underscores: false,
        host_whitelist: false,
        host_blacklist: false,
        allow_trailing_dot: false,
        allow_protocol_relative_urls: false,
        disallow_auth: false
    }
    
    isURL(string, options)
    

    host_whitelist and host_blacklist can be arrays of hosts. They also support regular expressions.

    let options = {
        host_blacklist: ['foo.com', 'bar.com'],
    }
    
    isURL('http://foobar.com', options) // => true
    isURL('http://foo.bar.com/', options) // => true
    isURL('http://qux.com', options) // => true
    
    isURL('http://bar.com/', options) // => false
    isURL('http://foo.com/', options) // => false
    
    
    options = {
        host_blacklist: ['bar.com', 'foo.com', /\.foo\.com$/],
    }
    
    isURL('http://foobar.com', options) // => true
    isURL('http://foo.bar.com/', options) // => true
    isURL('http://qux.com', options) // => true
    
    isURL('http://bar.com/', options) // => false
    isURL('http://foo.com/', options) // => false
    isURL('http://images.foo.com/', options) // => false
    isURL('http://cdn.foo.com/', options) // => false
    isURL('http://a.b.c.foo.com/', options) // => false
    

提交回复
热议问题