技术问询:如何提取当前URL域名并去除点号实现多站统一跳转
Solution for Dynamic Domain-Based Redirects to Ecommerce Cart Sites
Got it, here's a clean, reusable way to handle this cross-site redirect logic without maintaining separate codebases. The core idea is to dynamically extract and transform the current domain to build your target cart URL:
Step-by-Step Breakdown
- Grab the current domain: Use
window.location.hostnameto get the full domain of the current page (e.g.,site.co.ukorsite.us). - Strip out all dots: Use a regex to remove every
.from the domain string—this turnssite.co.ukintositecoukandsite.usintositeus. - Build the target URL: Append the cleaned domain to your fixed ecommerce cart base (
ecommercesite.com). - Implement the redirect/link: Either auto-redirect the user or update a link element for manual clicks.
Code Examples
Auto-Redirect on Page Load
If you want users to be sent straight to the cart site when they land on site.co.uk or site.us:
// Extract current domain const currentDomain = window.location.hostname; // Remove all period characters const cleanedDomain = currentDomain.replace(/\./g, ''); // Construct full cart URL const targetCartUrl = `https://${cleanedDomain}.ecommercesite.com`; // Trigger redirect window.location.href = targetCartUrl;
Dynamic Clickable Link
If you need a user-activated link instead of an auto-redirect:
<!-- Your HTML link placeholder --> <a id="shoppingCartLink" href="#">Visit Shopping Cart</a> <script> // Wait for the page to fully load before updating the link document.addEventListener('DOMContentLoaded', () => { const currentDomain = window.location.hostname; const cleanedDomain = currentDomain.replace(/\./g, ''); const targetCartUrl = `https://${cleanedDomain}.ecommercesite.com`; // Update the link's href attribute const cartLink = document.getElementById('shoppingCartLink'); cartLink.href = targetCartUrl; }); </script>
Optional: Handle Subdomains (e.g., www.)
If your sites might have a www. prefix, add an extra step to strip that out first:
// Remove www. if present, then strip all dots const cleanedDomain = currentDomain.replace(/^www\./, '').replace(/\./g, '');
This approach keeps your code DRY (Don't Repeat Yourself) and works seamlessly for any future regional sites you add (like site.ca → siteca.ecommercesite.com).
内容的提问来源于stack exchange,提问作者Henry Aspden
相关产品推荐
相关产品推荐

