Revela-Frontend/public/search.js
David Reed 9fa709d98f
prefix scripted elements with uv-, refactor search
Easier modification of the search engine by storing it in HTML
More effective process for picking a URL
2022-12-03 14:57:42 -05:00

32 lines
958 B
JavaScript

"use strict";
/**
*
* @param {string} input
* @param {string} template Template for a search query.
* @returns {string} Fully qualified URL
*/
function search(input, template) {
try {
// input is a valid URL:
// eg: https://example.com, https://example.com/test?q=param
return new URL(input).toString();
} catch (err) {
// input was not a valid URL
}
try {
// input is a valid URL when http:// is added to the start:
// eg: example.com, https://example.com/test?q=param
const url = new URL(`http://${input}`);
// only if the hostname has a TLD/subdomain
if (url.hostname.includes(".")) return url.toString();
} catch (err) {
// input was not valid URL
}
// input may have been a valid URL, however the hostname was invalid
// Attempts to convert the input to a fully qualified URL have failed
// Treat the input as a search query
return template.replace("%s", encodeURIComponent(input));
}