@mikezimm/fps-core-v7
Version:
Library of reusable core interfaces, types and constants migrated from fps-library-v2
41 lines (35 loc) • 2.12 kB
JavaScript
/**
* Here is the JavaScript code:
Explanation of the regex:
^ asserts the position at the start of the string.
(?:https?:\/\/)? matches the protocol part (http:// or https://) but does not capture it (?: makes it a non-capturing group).
(?:www\.)? matches www. if it is present but does not capture it.
([^\.]+) captures one or more characters that are not a dot (.) and stores them in a capturing group. This represents the main domain name.
\. matches the following dot.
This regex will work for typical URLs with the http or https protocols, optionally prefixed by www.. It captures the domain name part before the first dot in the URL.
const url = "https://www.bing.com?searcharam=X";
const domain = getDomain(url);
console.log(domain); // Outputs: bing
Explanation of the changes:
The regex now captures the domain part of the URL in a more generic way by matching ([^:\/?\n]+), which captures the full domain part before the TLD.
The split and extraction part ensures that if there are subdomains, we get the correct main domain by splitting the captured part by . and returning the second-to-last part.
(?:[a-z]{2,6}) matches the TLD which is assumed to be 2 to 6 letters long.
This approach should work for URLs with or without subdomains, extracting the correct main domain name in various scenarios.
* @param url
* @returns
*/
export function getDomain(url) {
// const regex = /^(?:https?:\/\/)?(?:www\.)?([^.]+)\./i;
// const match = url.match(regex);
// return match ? match[1] : null;
// const regex = /^(?:https?:\/\/)?(?:[^@/\n]+@)?(?:www\.)?([^:/?\n]+)\.(?:[a-z]{2,6})(?:[/\n]|\?|$)/i;
const regex = /^(?:https?:\/\/)?(?:[^@/\n]+@)?(?:www\.)?([^:/?\n]+)/i;
const match = url.match(regex);
if (match && match[1]) {
const parts = match[1].split('.');
return parts.length > 1 ? parts[parts.length - 2] : parts[0];
}
// 2024-09-22: changed from return null to return '' to pass typing
return '';
}
//# sourceMappingURL=getDomains.js.map