index.js 856 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * Expose `isUrl`.
  3. */
  4. module.exports = isUrl;
  5. /**
  6. * RegExps.
  7. * A URL must match #1 and then at least one of #2/#3.
  8. * Use two levels of REs to avoid REDOS.
  9. */
  10. var protocolAndDomainRE = /^(?:\w+:)?\/\/(\S+)$/;
  11. var localhostDomainRE = /^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/
  12. var nonLocalhostDomainRE = /^[^\s\.]+\.\S{2,}$/;
  13. /**
  14. * Loosely validate a URL `string`.
  15. *
  16. * @param {String} string
  17. * @return {Boolean}
  18. */
  19. function isUrl(string){
  20. if (typeof string !== 'string') {
  21. return false;
  22. }
  23. var match = string.match(protocolAndDomainRE);
  24. if (!match) {
  25. return false;
  26. }
  27. var everythingAfterProtocol = match[1];
  28. if (!everythingAfterProtocol) {
  29. return false;
  30. }
  31. if (localhostDomainRE.test(everythingAfterProtocol) ||
  32. nonLocalhostDomainRE.test(everythingAfterProtocol)) {
  33. return true;
  34. }
  35. return false;
  36. }