JAVASCRIPT

Extracting All URLs from Text

Discover and extract all HTTP/HTTPS URLs present within a block of text using a JavaScript regular expression, perfect for content parsing or link collection.

const extractUrls = (text) => {
  const urlRegex = /(https?:\/\/[^\s]+)/g;
  return text.match(urlRegex) || [];
};

const text = "Visit our site at https://www.example.com or our blog http://blog.example.org. Invalid link: ftp://example.net";
const urls = extractUrls(text);
console.log(urls);
// Expected: ["https://www.example.com", "http://blog.example.org"]
How it works: This `extractUrls` function utilizes a regular expression `(https?:\/\/[^\s]+)/g` to find all occurrences of URLs starting with 'http://' or 'https://' followed by any non-whitespace characters. The 'g' (global) flag ensures all matches are found, returning an array of found URLs or an empty array if none are present.

Need help integrating this into your project?

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

Hire DigitalCodeLabs