JAVASCRIPT
Extract All URLs from a String Using Regex
Learn how to extract all valid URLs (HTTP/HTTPS) from any given text string in JavaScript using a powerful regular expression, perfect for content parsing.
function extractUrls(text) {
const urlRegex = new RegExp(
/(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 matches = text.match(urlRegex);
return matches || [];
}
// Usage:
// const text = "Visit our website at https://www.example.com or check out http://blog.test.org for more info.";
// console.log(extractUrls(text));
// Output: ["https://www.example.com", "http://blog.test.org"]
How it works: This JavaScript function `extractUrls` takes a string as input and returns an array of all URLs found within it. It uses a comprehensive regular expression that targets common URL patterns, including `http://`, `https://`, and `www.` prefixes, as well as domain names. The `g` flag ensures all matches are found, and the `i` flag makes the search case-insensitive.