JAVASCRIPT

Extract All URLs (HTTP/HTTPS) from a String

Learn to efficiently extract all complete HTTP or HTTPS URLs, including subdomains and paths, from any given string using JavaScript regular expressions.

const text = "Visit our site at https://www.example.com/page and also http://sub.domain.net/path?id=123. API docs: https://api.example.org";
const urlRegex = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/[a-zA-Z0-9]+\.[^\s]{2,}|[a-zA-Z0-9]+\.[^\s]{2,})/gi;
const urls = text.match(urlRegex);
console.log(urls);
How it works: This JavaScript snippet uses a regular expression to find and extract all occurrences of valid HTTP or HTTPS URLs within a given string. The `match()` method, combined with the global (`g`) and case-insensitive (`i`) flags, returns an array of all matched URL strings, making it ideal for parsing links from user-generated content or text.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs