Regex patterns/Validation

HTTP/HTTPS URL

Accepts http and https URLs without pretending to parse every corner of the spec.

/^https?://[^\s/$.?#][^\s]*$/
Open it in Rex

The problem

Check that a string is an http or https web address before linking to it or fetching it.

How it reads

starthttpsskip://[^\s/$.?#][^\s]repeatskipend

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^https?://[^\s/$.?#][…In order:
  2. ^The start of the text (or of a line with the m flag)
  3. hThe character "h"
  4. tThe character "t"
  5. tThe character "t"
  6. pThe character "p"
  7. s?The character "s", optionally (zero or one time)
  8. :The character ":"
  9. /The character "/"
  10. /The character "/"
  11. [^\s/$.?#]Any character except whitespace, "/", "$", ".", "?" or "#"
  12. [^\s]*Any character except whitespace, any number of times, including none, as many as possible
  13. $The end of the text (or of a line with the m flag)

Matches

  • https://example.com/docs?page=2
  • http://localhost:3000
  • https://a.io

Does not match

  • ftp://files.example.com
  • just text
  • https://
  • example.com

Where it bites

  • In JavaScript, `new URL(value)` inside a try/catch is both more correct and easier to read. Reach for this pattern when you need to find URLs inside a larger block of text, not when validating one field.
  • It accepts anything after the host, including characters a browser would reject, because the alternative is a pattern nobody can read.
  • Other schemes — mailto:, ftp:, data: — are rejected by design.

More validation patterns