Open In App

How to Extract URLs from a String in JavaScript ?

Last Updated : 01 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are given a string str which consists of a hyperlink or URL present in it. We need to extract the URL from the string using JavaScript. The URL must be complete and you need to print the entire URL.

Example:

Input :-
str = "Platform for geeks: https://www.geeksforgeeks.org"
Output :-
https://www.geeksforgeeks.org
Explanation:
In the input string "https://www.geeksForgeeks.org" is a URL and we are required to extract this URL.

Approaches to extract URLs from a string in JavaScript:

  • Using Regular Expressions
  • Using split() Method

Approach 1: Using Regular Expressions

In this approach, we use the match method to find the first occurrence of a URL in the string. The regular expression `/https?:\/\/[^\s]+/` matches any string that starts with http or https, followed by one or more non-space characters. The [0] at the end of the match method returns the first match which is the entire URL present in the string.

Example: Below is the implementation of this approach

Javascript




let str = "Platform for geeks: https://www.geeksforgeeks.org";
let res = str.match(/https?:\/\/[^\s]+/)[0];
console.log("The extracted URL from given string is:- " + res);


Output

The extracted URL from given string is:- https://www.geeksforgeeks.org

Approach 2: Using the split() Method

In this approach, we use the split() method to split the string into an array of words and then we use the find method to find the first word that starts with http or https. This approach assumes that the URL is separated from the rest of the string by whitespaces meaning that there shouldn’t be any whitespaces in the URL .

Example: Below is the implementation of this approach

Javascript




let str = "Platform for geeks: https://www.geeksforgeeks.org";
let res = str.split(" ").find(word => word.startsWith("http"));
console.log("The extracted URL from given string is: " + res);


Output

The extracted URL from given string is: https://www.geeksforgeeks.org

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads