Skip to content

Instantly share code, notes, and snippets.

@AnandPilania
Last active March 22, 2024 03:20
Show Gist options
  • Save AnandPilania/c4347005b220b348222b441287c05199 to your computer and use it in GitHub Desktop.
Save AnandPilania/c4347005b220b348222b441287c05199 to your computer and use it in GitHub Desktop.
URL Parser - Easily extract protocol, host, path, query parameters, and more from any URL string (w/o URLSearchParams API).
/*
This JavaScript function parseURL takes a URL string as input and parses it into its various
components such as protocol, host, path, query parameters, and relative path. It utilizes
regular expressions to extract these components efficiently. The parsed components are then
encapsulated within an object for convenient access and manipulation in your code. This can
be useful in scenarios where you need to extract specific parts of a URL or analyze and modify
URLs dynamically within your web applications.
*/
function parseURL(url) {
if (typeof url !== "string")
return {};
var matches = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/),
query = matches[6] || "",
fragment = matches[8] || "";
return {
protocol: matches[2],
host: matches[4],
path: matches[5],
query: query,
relative: matches[5] + query + fragment
};
}
/*
This JavaScript function utilizes the URLSearchParams API to parse URLs,
extracting components such as protocol, host, path, query parameters,
and fragment identifier. It offers a modern and efficient approach to
URL parsing, ensuring simplicity and accuracy in handling URL data
within your applications.
*/
function parseURL(url) {
if (typeof url !== "string")
return {};
var parsedURL = new URL(url);
var protocol = parsedURL.protocol;
var host = parsedURL.host;
var path = parsedURL.pathname;
var query = parsedURL.searchParams;
var fragment = parsedURL.hash;
var queryParams = {};
query.forEach(function(value, key) {
queryParams[key] = value || true;
});
return {
protocol: protocol,
host: host,
path: path,
query: queryParams,
relative: path + parsedURL.search + fragment
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment