find urls in a string using regex in javascript

To find urls in a string using regex in JavaScript, you can use the match() method and a regular expression pattern that matches urls.

Here is an example code snippet:

index.tsx
const text = 'Lorem ipsum dolor sit amet, https://example.com consectetur adipiscing elit, sed do eiusmod tempor http://example.org incididunt ut labore et dolore magna aliqua.';

const urlRegex = /(https?:\/\/[^\s]+)/g;
const urls = text.match(urlRegex);

console.log(urls); // ["https://example.com", "http://example.org"]
325 chars
7 lines

In this code snippet, we define a regular expression pattern /(https?:\/\/[^\s]+)/g that matches urls starting with http:// or https:// and continuing until the next whitespace character.

We then use the match() method on the input string text with the regular expression urlRegex to extract all the urls in the string.

The match() method returns an array of matched urls, which we log to the console in this example.

gistlibby LogSnag