检测所选文本是否跨越整行或多行

发布于 2024-12-27 19:31:58 字数 510 浏览 0 评论 0原文

我正在尝试自动检测文本区域的选择是否包含新行,或者是否已选择整行。

例如

  • [abc def] xyz =>应该为 false,因为只选择了 [abc def]
  • [abc def xyz] =>应该为 true,因为已选择整行
  • 选择跨越多行 (true):

    <前><代码> abc [def xyz abc 定义 xyz abc def] xyz

这将检测最后一种情况:

var range = getTextAreaSelection(textarea),
    selection = textarea.value.substring(range[0], range[1]);

if(selection.indexOf('\n') !== -1)
  // do stuff...

但是我如何处理其他两种情况?

I'm trying to auto-detect if the selection of a textarea contains new lines, or if the full line has been selected.

For example

  • [abc def] xyz => should be false, because only [abc def] is selected
  • [abc def xyz] => should be true, because the entire line has been selected
  • the selection spans across multiple lines (true):

     abc [def xyz
     abc def xyz
     abc def] xyz
    

This will detect the last case:

var range = getTextAreaSelection(textarea),
    selection = textarea.value.substring(range[0], range[1]);

if(selection.indexOf('\n') !== -1)
  // do stuff...

But how do I handle the other two?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

友谊不毕业 2025-01-03 19:31:58

您可以检查之前/之后的字符是什么:

textarea.value.charAt(range[0] - 1); // if it's `\r` or `\n` it's the first char of a line
textarea.value.charAt(range[1] + 1); // same fot last char of a line

如果其中一个或两个返回空字符串,则它是文本区域值的开头/结尾,因此也算作整行。

You could check what the character before/after is:

textarea.value.charAt(range[0] - 1); // if it's `\r` or `\n` it's the first char of a line
textarea.value.charAt(range[1] + 1); // same fot last char of a line

If either or both return an empty string, it's the beginning/ending of the textarea value so that would also count as a full line.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文