How to Extract a URL from a String in JavaScript?

Estimated read time 1 min read

To extract a URL from a string in JavaScript, you can use a regular expression. Here’s an example:

const string = "Here's a URL:";
const urlRegex = /(https?:\/\/[^\s]+)/g;
const urls = string.match(urlRegex);
console.log(urls); // Output: [""]

Here’s what the regular expression does:

  • (https?:\/\/ – match “http://” or “https://”
  • [^\s]+) – match any non-space characters until the end of the URL

The g flag at the end of the regular expression enables a global search, which means it will find all occurrences of URLs in the string.

The string.match(urlRegex) method returns an array of all matches. In this case, it will return an array with a single element that contains the URL.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply