如何用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); } }
原理说明
- 首先获取完整的hash部分(包含#号及后续所有内容)
- 通过正则表达式精准匹配
:~:text=开头的片段:([^,]+)捕获起始文本(直到遇到逗号或结束)(?:,(.+))?可选捕获结束文本(如果存在逗号分隔的内容)
- 用
decodeURIComponent解码URL编码的特殊字符,还原原始文本内容
内容的提问来源于stack exchange,提问作者Joel Davis
相关产品推荐
相关产品推荐

