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

如何使用jQuery从分享链接中提取'whatsapp'字符串?

解决方案

要从类似https://api.whatsapp.com/send?text=...的链接中提取出whatsapp,可以通过以下两种简单可靠的方法实现:

方案一:使用split()拆分字符串

利用链接的域名结构特征,通过.拆分后直接提取目标内容:

jQuery('div.share_block > div > a').click(function(){
    // 获取完整的分享链接
    const fullLink = jQuery(this).attr('href');
    // 按域名的点分隔符拆分,提取"whatsapp"
    const _shareLink = fullLink.split('.')[1];
    
    const visit_link = jQuery(this).prevUntil('div.offer_hover_block > a').text();
  
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        'event': 'whatsapp_click',
        'carouselHref' : _shareLink,
        'pageName' : visit_link
    });
});

方案二:使用正则表达式匹配(更鲁棒)

如果链接结构可能存在变化,正则匹配能适配更多场景,直接精准匹配whatsapp:

jQuery('div.share_block > div > a').click(function(){
    const fullLink = jQuery(this).attr('href');
    // 正则匹配链接中的"whatsapp"字符
    const matchResult = fullLink.match(/whatsapp/);
    // 匹配成功则取结果,否则设为空字符串
    const _shareLink = matchResult ? matchResult[0] : '';
    
    const visit_link = jQuery(this).prevUntil('div.offer_hover_block > a').text();
  
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        'event': 'whatsapp_click',
        'carouselHref' : _shareLink,
        'pageName' : visit_link
    });
});

关键说明

原代码中jQuery(this).attr('href').filter() === "whatsapp"的写法错误,filter()是jQuery集合的操作方法,不能直接用于字符串处理。两种方案中:

  • 方案一适合链接结构固定的场景(whatsapp始终在域名的第二个点分隔段);
  • 方案二适配更多可能的链接格式,容错性更强。

内容的提问来源于stack exchange,提问作者Ameno

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:20:25