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

如何用JavaScript获取URL中#:~:text=后的内容?

获取URL中Scroll To Text Fragment的内容

普通的window.location.hash方法看似能拿到#后的片段,但因为Scroll To Text Fragment(:~:text=)是附加在hash中的特殊格式标识符,直接截取无法精准提取目标内容,需要通过正则解析来实现。

解决方案代码

function getTextFragmentContent() {
  const hash = window.location.hash;
  // 匹配:~:text=后的起始文本,以及可选的结束文本
  const textFragmentMatch = hash.match(/:~:text=([^,]+)(?:,(.+))?$/);
  
  if (!textFragmentMatch) return null;

  // 解码URL编码的字符(比如%20转为空格)
  const result = {
    startText: decodeURIComponent(textFragmentMatch[1])
  };
  // 如果存在结束文本,一并解码返回
  if (textFragmentMatch[2]) {
    result.endText = decodeURIComponent(textFragmentMatch[2]);
  }

  return result;
}

// 使用示例
const fragment = getTextFragmentContent();
if (fragment) {
  console.log('起始文本:', fragment.startText);
  if (fragment.endText) {
    console.log('结束文本:', fragment.endText);
  }
}

原理说明

  1. 首先获取完整的hash部分(包含#号及后续所有内容)
  2. 通过正则表达式精准匹配:~:text=开头的片段:
    • ([^,]+) 捕获起始文本(直到遇到逗号或结束)
    • (?:,(.+))? 可选捕获结束文本(如果存在逗号分隔的内容)
  3. 用decodeURIComponent解码URL编码的特殊字符,还原原始文本内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 18:25:02