Skip to content

Instantly share code, notes, and snippets.

@Mathews2115
Created August 21, 2019 22:53
Show Gist options
  • Save Mathews2115/c3693eb90a2fad30f1a8b59e94e43b1d to your computer and use it in GitHub Desktop.
Save Mathews2115/c3693eb90a2fad30f1a8b59e94e43b1d to your computer and use it in GitHub Desktop.
handy regex - remove subdomain from full url (not perfect)
/**
* Returns a url without the subdomain. If no subdomain exists, just returns the same url
* @param {string} fullUrl - Example: https://sub.domain.com
* @returns {string} - Url without subdomain - Example: https://domain.com
*/
export const removeSubdomainFrom = function(fullUrl = '') {
// configure host strings
const regex = {
protocol: new RegExp(/http(s)*:\/\//), // gets the http:// OR https:// from url string
subdomain: new RegExp(/^[^.]*\.(?=\w+\.\w+$)/) // gets the http(s)://subdomain portion from url string
}
let newUrl = fullUrl
let protocol = regex.protocol.exec(fullUrl) // save protocol from provided Url so we can reapply it to the non-subdomain
if (protocol && protocol.length) {
// if https://subdomain exists, just remove the subdomain from it
newUrl = fullUrl.replace(regex.subdomain, protocol[0])
}
return newUrl
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment