gpt4 book ai didi

javascript - 获取光标正在触摸(或在其中)JavaScript 的完整单词

转载 作者:行者123 更新时间:2023-12-01 15:20:52 25 4
gpt4 key购买 nike

使用 native 输入字段,我可以很好地获得光标的位置。任何突出显示的文本也很容易。

// get cursor position
console.log(input.selectionStart);
// get highlighted text
console.log(input.value.substr(input.selectionStart, input.selectionEnd - input.selectionStart));

但是我们怎样才能得到光标所接触的完整单词呢?
this is a |sent|ence|
问题:

如果每个管道都是一个潜在的光标位置、箭头键或在单词周围单击,我们如何获得完整的单词“sentence”?

子问题:
  • 此解决方案的范围或正则表达式?
  • RegEx 可以按字符串中的位置环顾四周吗?
  • 如果给定字符串中的字符位置,Regex 可以找到单词

  • 研究:
    https://javascript.info/selection-range .
    https://developer.mozilla.org/en-US/docs/Web/API/range .
    https://developer.mozilla.org/en-US/docs/Web/API/Document/caretRangeFromPoint (仅限 Chrome )

    工作 CodePen with RegEx从 friend 那里。

    最佳答案

    您可以使用一些正则表达式来查找

  • 任何包含以 position 结尾的单词字符的字符串
  • 任何包含从 position 开始的单词字符的字符串


  • const [$show, $input] = document.querySelectorAll('span,textarea')
    const getWord = (s, pos) => {
    const n = s.substring(pos).match(/^[a-zA-Z0-9-_]+/)
    const p = s.substring(0, pos).match(/[a-zA-Z0-9-_]+$/)
    // if you really only want the word if you click at start or between
    // but not at end instead use if (!n) return
    if(!p && !n) return ''
    return (p || '') + (n || '')
    }
    const showWord = e => $show.innerText = getWord(e.target.value, e.target.selectionStart)
    $input.addEventListener('click', showWord)
    $input.addEventListener('input', showWord)
    textarea{
    width: 500px;
    height: 500px;
    }
    <span id="inputshow"></span><br/>
    <textarea>In computer science, an x-fast trie is a data structure for storing integers from a bounded domain. It supports exact and predecessor or successor queries in time O(log log M), using O(n log M) space, where n is the number of stored values and M is the maximum value in the domain. The structure was proposed by Dan Willard in 1982,[1] along with the more complicated y-fast trie, as a way to improve the space usage of van Emde Boas trees, while retaining the O(log log M) query time. </textarea>

    关于javascript - 获取光标正在触摸(或在其中)JavaScript 的完整单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61598927/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com