How to Extract URLs from a String in JavaScript ?
Last Updated :
29 May, 2024
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:
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);
OutputThe extracted URL from given string is:- https://www.geeksforgeeks.org
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);
OutputThe extracted URL from given string is: https://www.geeksforgeeks.org
Approach 3: Using the URL Constructor
In this approach, we iterate over each word in the string, attempt to create a URL object, and check if it is a valid URL. This method is more robust as it explicitly verifies the validity of the URL.
Example: Below is the implementation of this approach:
JavaScript
let str = "Platform for geeks https://www.geeksforgeeks.org";
let words = str.split(/\s+/); // Using a regex to split by whitespace
let url = null; // Initialize url to null
for (let word of words) {
try {
let potentialUrl = new URL(word);
url = potentialUrl.href;
break;
} catch (e) {
// If the word is not a valid URL, it will throw an error which we ignore
}
}
if (url !== null) {
console.log("The extracted URL from given string is: " + url);
} else {
console.log("No URL found in the given string.");
}
OutputThe extracted URL from given string is: https://www.geeksforgeeks.org/
Similar Reads
How to Check if a String Contains a Valid URL Format in JavaScript ? A string containing a valid URL format adheres to standard conventions, comprising a scheme (e.g., "https://" or "https://"), domain, and optionally, a path, query parameters, and fragments. Ensuring this format is crucial for data consistency and accurate handling of URLs in applications.There are s
2 min read
JavaScript Program to get Query String Values Getting query string values in JavaScript refers to extracting parameters from a URL after the "?" symbol. It allows developers to capture user input or state information passed through URLs for dynamic web content and processing within a web application. Table of Content Using URLSearchParamsUsing
2 min read
JavaScript URLify a given string (Replace spaces is %20) In this article, we are going to discuss how can we URLify a given string using JavaScript. In which we will be transforming the spaces within the input strings into the "%20" sequence. The process of URLLification consists of replacing these spaces with the '%20' encoding. This task is essential fo
6 min read
JavaScript Program to find the Index of the First Occurrence of a Substring in a String In this article, we will find the index of the first occurrence of a substring in a string using JavaScript. An essential task in JavaScript programming is searching for substrings within a string. Finding the index of the first occurrence of a substring is a typical necessity, whether you are const
6 min read
Extract a Number from a String using JavaScript We will extract the numbers if they exist in a given string. We will have a string and we need to print the numbers that are present in the given string in the console.Below are the methods to extract a number from string using JavaScript:Table of ContentUsing JavaScript match method with regExUsing
4 min read