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
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Laravel user password being updated via artisan tinker with Hash::make
Web Development

How to Change a User Password in Laravel

6 Min Read
Check if an element is hidden or visible with jQuery
Web Development

How to Check if an Element Is Hidden or Visible with jQuery

4 Min Read
Display only the current date in Laravel using Carbon
Web Development

How to Display Only the Current Date in Laravel (Carbon Examples)

4 Min Read
Laravel last inserted ID — Eloquent save populates model primary key illustration
Web Development

How to Retrieve the Last Inserted ID in Laravel Eloquent

8 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?