URL Validation in JS
Match http and https URLs with optional www prefix, paths, query strings, and fragments.
Try it in the JS tester →Pattern
regexJS
https?:\/\/(?:www\.)?[\w\-]+(?:\.[\w\-]+)+[\w\-._~:/?#\[\]@!$&'()*+,;=%]* (flags: gi)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("https?:\\/\\/(?:www\\.)?[\\w\\-]+(?:\\.[\\w\\-]+)+[\\w\\-._~:/?#\\[\\]@!$&'()*+,;=%]*", "gi");
const input = "https://www.example.com";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
Starts with http:// or https://, optional www., then one or more domain labels separated by dots, followed by any valid URL characters for the path and query.
Examples
Input
https://www.example.comMatches
https://www.example.com
Input
http://api.example.org/v1/users?id=42Matches
http://api.example.org/v1/users?id=42
Input
not a urlNo match
—