You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术问询:如何提取当前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.hostname to get the full domain of the current page (e.g., site.co.uk or site.us).
  • Strip out all dots: Use a regex to remove every . from the domain string—this turns site.co.uk into sitecouk and site.us into siteus.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 06:53:17