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

请求修改复制文本添加来源链接的代码以截取指定格式URL

修改复制文本自动添加来源链接的代码

下面是修改后的代码,核心是通过正则表达式截取URL中/post/及后续数字部分的路径,替换原有的完整URL:

function addLink() {
    // 获取选中的文本并拼接附加信息
    var selection = window.getSelection();
    // 截取URL到/post/后的数字部分
    const baseUrl = document.location.href.match(/(https?:\/\/.+?\/post\/\d+)/)?.[1] || document.location.href;
    pagelink = ". Read more at: " + baseUrl;
    copytext = selection + pagelink;
    // 创建新容器存放处理后的文本
    newdiv = document.createElement('div');

    // 隐藏容器
    newdiv.style.position = 'absolute';
    newdiv.style.left = '-99999px';

    // 插入容器、填充文本并重新选中
    document.body.appendChild(newdiv);
    newdiv.innerHTML = copytext;
    selection.selectAllChildren(newdiv);

    window.setTimeout(function () {
        document.body.removeChild(newdiv);
    }, 100);
}
document.addEventListener('copy', addLink);

关键修改说明:

  • 使用正则表达式/(https?:\/\/.+?\/post\/\d+)/匹配URL中从协议开始,到/post/后数字段的部分:
    • https?:\/\/ 匹配HTTP/HTTPS协议
    • .+? 非贪婪匹配域名及前面的路径
    • \/post\/\d+ 匹配/post/后接一串数字的部分
  • 如果正则匹配失败(比如当前页面URL不符合规则),会 fallback 到原完整URL,避免出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:05:27