Skip to content

Instantly share code, notes, and snippets.

@nommiin
Created September 28, 2024 20:55
Show Gist options
  • Select an option

  • Save nommiin/c3ee9ddb8cda0d4e085e4aae41e962af to your computer and use it in GitHub Desktop.

Select an option

Save nommiin/c3ee9ddb8cda0d4e085e4aae41e962af to your computer and use it in GitHub Desktop.
Parse URL into a struct
/// @function url_parse(_url)
/// @author nommiin
/// @argument {String} _url - The URL to parse into a struct
/// @returns {Struct}
function url_parse(_url) {
var data = {
href: _url,
protocol: undefined,
hostname: undefined,
port: undefined,
pathname: undefined,
search: undefined,
hash: undefined
};
var state = 0, hostname = undefined, protocol_ind = -1, hostname_ind = -1, pathname_ind = -1;
for(var i = 1; i < string_length(_url) + 1; i++) {
var char = string_char_at(_url, i);
if (state == 0) {
if (string_copy(_url, i, 3) == "://") {
data.protocol = string_copy(_url, 1, i);
i += 3;
protocol_ind = i;
state = 1;
}
} else if (state == 1) {
if (char == "/" || char == "?") {
hostname = string_copy(_url, protocol_ind, i - protocol_ind);
hostname_ind = i;
state = (char == "/" ? 2 : 3);
if (state == 3) {
pathname_ind = hostname_ind;
}
}
} else if (state == 2) {
if (char == "?" || char == "#") {
data.pathname = string_copy(_url, hostname_ind, i - hostname_ind);
pathname_ind = i;
state = (char == "?" ? 3 : 4);
}
} else if (state == 3) {
if (char == "#") {
data.search = string_copy(_url, pathname_ind, i - pathname_ind);
pathname_ind = i;
state = 4;
}
} else if (state == 4) {
data.hash = string_copy(_url, pathname_ind, string_length(_url));
break;
}
}
if (state == 1) {
hostname = string_copy(_url, protocol_ind, string_length(_url));
} else if (state == 2) {
data.pathname = string_copy(_url, hostname_ind, string_length(_url));
} else if (state == 3) {
data.search = string_copy(_url, pathname_ind, string_length(_url));
}
var port_ind = string_pos(":", hostname);
if (port_ind > 0) {
data.hostname = string_copy(hostname, 1, port_ind - 1);
data.port = string_copy(hostname, port_ind + 1, string_length(hostname));
} else {
data.hostname = hostname;
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment