Regex for URL Validation

Test a regex that matches http and https URLs. Check it against valid and invalid links and learn when to use the URL constructor instead.

Part of the free Regex Tester. Runs in your browser — nothing is uploaded.

Regex for URL Validation

This pattern matches http and https URLs with a hostname and an optional path, query and fragment. It is useful for finding links in text, but in code the built-in URL constructor is a stricter validator.

Worked example: Valid and invalid links

Pattern /^https?:\/\/[\w.-]+(?:\.[a-z]{2,})(?:[\/?#]\S*)?$/i — test strings

^https?:\/\/[\w.-]+(?:\.[a-z]{2,})(?:[\/?#]\S*)?$

https://www.kaviforge.com
http://example.com/path?x=1#top
ftp://example.com
http:/missing-slash.com
just text

Result for each line

✓ match     https://www.kaviforge.com
✓ match     http://example.com/path?x=1#top
✗ no match  ftp://example.com
✗ no match  http:/missing-slash.com
✗ no match  just text

Practical tip

In JavaScript, wrap new URL(input) in try/catch for validation. Use a regex when you need to scan free text for links.

How to use this Regex Tester

  1. 1Use the live tool above — it runs entirely in your browser and never uploads your data.
  2. 2Paste the sample from the worked example, or use your own input.
  3. 3Copy the result, then adapt the same steps in your editor, script, or pipeline.

Regex for URL Validation FAQs

Why use new URL() instead of a regex?

The URL constructor follows the real URL parsing rules, so it handles ports, IPv6, encoding and edge cases a hand-written regex will miss.

How do I allow URLs without http?

Make the scheme optional with (?:https?:\/\/)? at the start, but be aware this also matches plain words that look like domains.

More Regex Tester pages

Open the full Regex Tester tool →