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

如何修改选区至前后空格或换行以获取完整YouTube URL

问题:点击按钮无法选中完整YouTube URL

当光标置于YouTube URL内部时,点击按钮只能输出URL的部分内容,需要实现点击按钮后自动选中从前一个空格/换行到下一个空格/换行之间的完整URL。

解决方案

替换原有的选区逻辑,通过Range对象精准定位URL的前后边界:

$('button').on('click', function(){
  const selection = window.getSelection();
  if (!selection.rangeCount) return;

  const range = selection.getRangeAt(0);
  const textNode = range.startContainer;
  const text = textNode.textContent;
  let startPos = range.startOffset;
  let endPos = range.startOffset;

  // 向前查找:找到第一个空格/换行,或文本开头
  while (startPos > 0 && !/\s/.test(text[startPos - 1])) {
    startPos--;
  }

  // 向后查找:找到第一个空格/换行,或文本结尾
  while (endPos < text.length && !/\s/.test(text[endPos])) {
    endPos++;
  }

  // 调整选区范围
  range.setStart(textNode, startPos);
  range.setEnd(textNode, endPos);
  selection.removeAllRanges();
  selection.addRange(range);

  console.log(selection.toString());
});

原代码问题分析

原代码使用selection?.modify('move', 'backward', 'word')和selection?.modify('extend', 'forward', 'word'),这里的word单位会把URL中的特殊符号(如://、?、=)视为单词分隔符,导致只能选中URL的片段(比如https、www.youtube.com这类拆分后的部分),无法覆盖完整的URL。

而通过遍历文本节点查找空格/换行的方式,能准确识别URL作为一个整体的边界,确保选中完整的URL内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:27:14