jquery 如何修改选择到上一个和下一个空格或新行

p3rjfoxz  于 2023-06-22  发布在  jQuery
关注(0)|答案(1)|浏览(109)
$('button').on('click', function(){
const selection = window.getSelection();
selection?.modify('move', 'backward', 'word');
selection?.modify('extend', 'forward', 'word');
console.log(selection.toString());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre contenteditable>
https://www.youtube.com/watch?v=vEQ8CXFWLZU
 https://www.youtube.com/watch?v=vEQ8CXFWLZU
lorem ipsum https://www.youtube.com/watch?v=vEQ8CXFWLZU
https://www.youtube.com/watch?v=vEQ8CXFWLZU lorem ipsum
 https://www.youtube.com/watch?v=vEQ8CXFWLZU lorem ipsum
</pre>
<button>CLICK</button>

将光标放在youtube url中
点击一个按钮,我需要在控制台的整个网址,而不仅仅是一部分
换句话说,我需要这样的东西:

selection?.modify('move', 'backward', 'to the previous space or new line');
selection?.modify('extend', 'forward', 'to the next space or new line');
2eafrhcq

2eafrhcq1#

在Regex的帮助下,您可以设置规则。

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

  let [bws, aws] = [false, false];

  let [
    [bn, bo],
    [an, ao]
  ] = [
    [selection.anchorNode, selection.anchorOffset],
    [selection.focusNode, selection.focusOffset]
  ]
  .sort(function(aa, bb) {
    return aa[1] - bb[1];
  });

  while (!bws && 0 < bo) {
    selection.setBaseAndExtent(bn, --bo, an, ao);

    if ((bws = (-1 !== selection.toString().search(/\r?\n| /)))) {
      ++bo;
    }
  }

  while (!aws && an.length >= ao + 1) {
    selection.setBaseAndExtent(bn, bo, an, ++ao);
    if ((aws = (-1 !== selection.toString().search(/\r?\n| /)))) {
      --ao;
    }
  }
  selection.setBaseAndExtent(bn, bo, an, ao);
  console.log(selection.toString());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre contenteditable>
https://www.youtube.com/watch?v=vEQ8CXFWLZU
 https://www.youtube.com/watch?v=vEQ8CXFWLZU
lorem ipsum https://www.youtube.com/watch?v=vEQ8CXFWLZU
https://www.youtube.com/watch?v=vEQ8CXFWLZU lorem ipsum
 https://www.youtube.com/watch?v=vEQ8CXFWLZU lorem ipsum
</pre>
<button>CLICK</button>

相关问题