Skip to content

Instantly share code, notes, and snippets.

@mark05e
Created May 29, 2023 20:00
Show Gist options
  • Save mark05e/16c3dd197be28a6749db17dfb86372b0 to your computer and use it in GitHub Desktop.
Save mark05e/16c3dd197be28a6749db17dfb86372b0 to your computer and use it in GitHub Desktop.
/**
* Replaces the domain of a URL with the domain of another URL.
*
* @param {string} url1 - The first URL containing the target domain to be replaced.
* @param {string} url2 - The second URL containing the replacement domain.
* @returns {string} - The modified URL with the domain replaced.
*/
function replaceDomain(url1, url2) {
// Regular expression pattern to match the domain of a URL
let urlRegex = /https:\/\/[^/]+/;
// Extract the domain from url1
let url1Domain = url1.match(urlRegex)[0];
// Extract the domain from url2
let url2Domain = url2.match(urlRegex)[0];
// Replace the domain in url2 with the domain from url1
return url2.replace(url2Domain, url1Domain);
}
function replaceDomain_test() {
let url1 = 'https://example.com/page1';
let url2 = 'https://test.com/page2';
let modifiedUrl = replaceDomain(url1, url2);
console.log(modifiedUrl); // https://example.com/page2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment