JAVASCRIPT
Extracting All URLs (HTTP/HTTPS) from a String
Discover how to efficiently extract all complete HTTP or HTTPS URLs present within a given text string using a powerful regular expression in JavaScript.
function extractUrls(text) {
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,})/g;
return text.match(urlRegex) || [];
}
// Examples:
// const sampleText = "Visit our site at https://www.example.com or check out http://blog.test.org. Invalid: not-a-url.";
// console.log(extractUrls(sampleText)); // ['https://www.example.com', 'http://blog.test.org']
How it works: This JavaScript snippet provides a function to find and extract all occurrences of full URLs (starting with `http://`, `https://`, or `www.`) from a given text. The regex uses the global flag (`g`) to find all matches, returning an array of found URLs or an empty array if none are present. It aims to capture common URL formats.