How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Check if a JavaScript String Is a Valid URL
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Check if a JavaScript String Is a Valid URL
Web Development

How to Check if a JavaScript String Is a Valid URL

how7o
By how7o
Last updated: May 22, 2026
5 Min Read
JavaScript check valid URL — URL constructor vs regex
SHARE

To javascript check valid url, the cleanest approach is the built-in URL constructor: new URL(string) throws on invalid input, succeeds on valid input. No regex, no edge cases, no maintenance. This guide shows the constructor pattern, the protocol-restrict trick to reject javascript: and mailto: URLs, and when a regex is still useful as a fallback.

Contents
  • TL;DR
  • The URL constructor
  • Restricting to http/https
  • The regex fallback
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 in Chromium, Firefox, Safari, and Node.js 22. Originally published 2022-12-21, rewritten and updated 2026-05-17.

TL;DR

function isValidUrl(input) {
  let url;
  try { url = new URL(input); }
  catch { return false; }
  return url.protocol === "http:" || url.protocol === "https:";
}

isValidUrl("https://how7o.com");           // true
isValidUrl("not a url");                   // false
isValidUrl("javascript:alert(1)");         // false  (protocol filtered)
isValidUrl("mailto:[email protected]");     // false  (protocol filtered)

The URL constructor

The URL constructor is part of the WHATWG URL Standard — the same parser browsers use for the address bar and <a href> attributes. Pass a string; you get a URL object back on success, or a TypeError on failure. Wrapping it in a try/catch turns parsing into a clean boolean check:

function isValidUrl(input) {
  try {
    new URL(input);
    return true;
  } catch {
    return false;
  }
}

That’s the whole solution for most use cases. Works in every modern browser, Node.js 12+, Deno, and Bun. No dependencies.

JavaScript check valid URL — URL constructor vs regex comparison

Restricting to http/https

The constructor accepts any valid URL — including mailto:, tel:, javascript:, data:, and other schemes. For most “is this a link?” checks you want web URLs only. Check protocol after the parse:

function isValidUrl(input) {
  let url;
  try { url = new URL(input); }
  catch { return false; }
  return url.protocol === "http:" || url.protocol === "https:";
}

Note the trailing colon — url.protocol returns "https:", not "https". Filtering out javascript: is especially important when the URL ends up in the DOM (e.g. assigned to <a href>), since javascript: URLs execute on click.

The regex fallback

If you absolutely can’t use the constructor — sandboxed runtime, ancient browser support, or a very specific structural check — here’s the classic regex pattern from the original source:

function isValidUrl(str) {
  const pattern = new RegExp(
    '^(https?:\\/\\/)?'                              // protocol (optional)
    + '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' // domain
    + '((\\d{1,3}\\.){3}\\d{1,3}))'                    // OR IPv4
    + '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'                // port + path
    + '(\\?[;&a-z\\d%_.~+=-]*)?'                       // query
    + '(\\#[-a-z\\d_]*)?$',                           // fragment
    'i'
  );
  return pattern.test(str);
}

Caveats: this regex doesn’t handle IPv6 hosts, internationalized domain names (IDN), or unusual ports correctly. For anything user-facing, the constructor is still the better choice.

Frequently asked questions

Why is the URL constructor better than a regex for javascript check valid url?

Because the URL constructor follows the official WHATWG URL Standard that browsers use natively — the same parser that resolves <a href> attributes and the address bar. Regexes always lag the spec, miss edge cases (IDN domains, IPv6 hosts, custom schemes), and need maintenance every time the spec changes. new URL(input) gets all of that for free.

Does new URL() work in all browsers?

Yes — every modern browser (Chrome, Firefox, Safari, Edge), every modern Node.js (12+), every Deno and Bun runtime. It’s part of the WHATWG URL Standard, has been ubiquitous since around 2017, and only Internet Explorer (now retired) didn’t support it.

How do I restrict to http or https URLs only?

After the new URL(...) succeeds, check url.protocol: return url.protocol === 'http:' || url.protocol === 'https:'. Without this filter, strings like 'mailto:[email protected]' and 'javascript:alert(1)' parse as valid URLs because they follow URL syntax — they’re just not the kind of URL you want.

Will new URL('example.com') succeed?

No — new URL('example.com') throws, because there’s no protocol. The URL constructor requires either an absolute URL (with scheme) or a base URL as the second argument: new URL('example.com', 'https://') would succeed. If you want to accept bare hostnames, prepend https:// before validating.

Is the regex version still useful?

Rarely — only when you genuinely can’t use modern JS (e.g. embedded in a sandbox that strips the URL constructor), or when you need to validate URL structure without the spec quirks (the constructor accepts some surprising inputs as valid, like 'http://////example.com'). For 99% of frontend and Node.js work, the constructor is the right tool.

Related guides

  • Laravel “in” Validation Rule
  • Check if the GD Library Is Installed in PHP

References

WHATWG URL Standard: url.spec.whatwg.org. MDN URL constructor: developer.mozilla.org/en-US/docs/Web/API/URL/URL.

TAGGED:JavaScriptSecurityValidation

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Pure-FTPd add user command line — pure-pw useradd flow on Linux How to Add a User to Pure-FTPd from the Command Line on Linux
Next Article Check Pure-FTPd installed on Linux — rpm and dpkg package queries How to Check if Pure-FTPd Is Installed on Linux
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026
Tailscale mesh — peer-to-peer connections between devices, coordination server
How to Install Tailscale on Ubuntu (Zero-Config Mesh VPN for Self-Hosters)
May 24, 2026

You Might Also Like

WooCommerce My Account login form hooks — five positions for injecting content
Web Development

How to Add a Link or Button After the Login Form in WooCommerce

6 Min Read
Laravel rollback specific migration — Artisan migrate:rollback --path command illustration
Web Development

How to Rollback a Specific Migration in Laravel

8 Min Read
WordPress too many redirects HTTPS — Cloudflare flexible SSL loop and the wp-config fix
Web Development

Fix ERR_TOO_MANY_REDIRECTS in WordPress After Switching to HTTPS

7 Min Read
Format a PHP number with leading zeros — sprintf and str_pad
Web Development

How to Format a Number with Leading Zeros in PHP

4 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?