use regex to find all links in javascript

To find all links in a JavaScript string using regular expressions, you can use the match() method with a regex pattern that matches links.

index.tsx
const text = "This is a link: https://www.example.com and this is another link: http://www.google.com";
const regex = /https?:\/\/(?:[a-z0-9]+(?:-[a-z0-9]+)*\.)+[a-z]{2,}(?::\d{1,5})?(?:\/[^\s]*)?/gi;
const links = text.match(regex);
console.log(links);
254 chars
5 lines

Explanation of regex pattern:

  • /https?:\/\// matches http:// or https://
  • (?:[a-z0-9]+(?:-[a-z0-9]+)*\.)+[a-z]{2,} matches the domain name (example: google.com).
  • (?::\d{1,5})? matches the optional port number (example: :8080).
  • (?:\/[^\s]*)? matches the optional path (example: /path/to/resource).

The g flag makes the regex search globally in the text, and the i flag makes it case-insensitive. The match() method returns an array of matched links.

gistlibby LogSnag