Regex tester

Regex for URLs

This pattern matches a full http or https URL: the scheme, a host that doesn't start with a dot or slash, and anything after it up to the first space.

^https?:\/\/[^\s/$.?#].[^\s]*$

The tester below has the pattern and some sample URLs loaded. Lines in the result matched; the others didn't.

Regex tester
Test textTEXT

Press Command or Control plus Enter to run. Tab inserts indentation; press Escape, then Tab, to leave the editor.

Result
Your result will appear here.
Ready7 lines · 144 chars

Find links inside a paragraph

To pull URLs out of running text, drop the ^ and $ anchors and stop at characters that usually end a link:

const LINK = /https?:\/\/[^\s<>"')\]]+/g;

"Docs at https://example.com/docs, or see http://localhost:3000."
  .match(LINK);
// ["https://example.com/docs,", "http://localhost:3000."]

// Trailing punctuation is part of the match, so trim it:
const links = (text) => (text.match(LINK) ?? []).map((url) => url.replace(/[.,;:!?]+$/, ""));

Validating a URL? Use new URL() instead

For checking a single value, such as a form field, the URL parser built into browsers and Node.js is stricter and handles ports, IPv6 hosts and international domains correctly:

function isHttpUrl(value) {
  try {
    const url = new URL(value);
    return url.protocol === "http:" || url.protocol === "https:";
  } catch {
    return false;
  }
}

isHttpUrl("https://example.com/a?b=1"); // true
isHttpUrl("javascript:alert(1)");       // false
isHttpUrl("example.com");               // false: no scheme

Security note

Before putting a user-supplied URL in an href, check that the scheme is http: or https:. A link like javascript:... runs code when clicked, and a loose regex without ^ can be fooled by a value that only contains https:// somewhere in the middle.

Frequently asked questions

How do I make the scheme optional, to match example.com too?

Make it optional with (?:https?:\/\/)?, but expect false positives such as file names like notes.txt. Requiring the scheme is much more reliable.

Does this match URLs with ports and query strings?

Yes. Everything after the host up to the first whitespace is accepted, including :3000, paths, ?query and #fragment.

Why do I get the trailing period or comma in my match?

Periods and commas are valid in URLs, so the regex can't tell they end the sentence. Strip trailing punctuation after matching, as in the example above.

More regex tester guides

Open the full regex tester →

From the blog