Validating a URL in Node.js

后端 未结 4 1488
我在风中等你
我在风中等你 2020-12-24 08:53

I want to validate a URL of the types:

  • www.google.com
  • http://www.google.com
  • google.com

4条回答
  •  悲哀的现实
    2020-12-24 09:19

    There is no need to use a third party library.

    To check if a string is a valid URL

      const URL = require("url").URL;
    
      const stringIsAValidUrl = (s) => {
        try {
          new URL(s);
          return true;
        } catch (err) {
          return false;
        }
      };
    
      stringIsAValidUrl("https://www.example.com:777/a/b?c=d&e=f#g"); //true
      stringIsAValidUrl("invalid"): //false
    

    Edit

    If you need to restrict the protocol to a range of protocols you can do something like this

    const { URL, parse } = require('url');
    
    const stringIsAValidUrl = (s, protocols) => {
        try {
            new URL(s);
            const parsed = parse(s);
            return protocols
                ? parsed.protocol
                    ? protocols.map(x => `${x.toLowerCase()}:`).includes(parsed.protocol)
                    : false
                : true;
        } catch (err) {
            return false;
        }
    };
    
    stringIsAValidUrl('abc://www.example.com:777/a/b?c=d&e=f#g', ['http', 'https']); // false
    stringIsAValidUrl('abc://www.example.com:777/a/b?c=d&e=f#g'); // true
    

    Edit

    Due to parse depreciation the code is simplified a little bit more. To address protocol only test returns true issue, I have to say this utility function is a template. You can adopt it to your use case easily. The above mentioned issue is covered by a simple test of url.host !== ""

    const { URL } = require('url');
    
    const stringIsAValidUrl = (s, protocols) => {
        try {
            url = new URL(s);
            return protocols
                ? url.protocol
                    ? protocols.map(x => `${x.toLowerCase()}:`).includes(url.protocol)
                    : false
                : true;
        } catch (err) {
            return false;
        }
    };
    

提交回复
热议问题