简体   繁体   中英

How to get single clicked word from textarea using JavaScript

Is it possible to get clicked word from textarea using jquery or javascript in IE and Firefox. Currently i'm using the below code and it's working perfectly fine in Chrome but it doesn't work at all in IE and Firefox.

<body>
<label for="result" style="display: none">Text</label>
<textarea id="result" rows="30" cols="100"></textarea>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>

    $("#result").click(function() {
        if($(this).val() !== null && $(this).val() !== ''){
            var selection = window.getSelection();
            selection.modify('extend', 'backward', 'word');
            var end = selection.toString();

            selection.modify('extend', 'forward', 'word');
            var start = selection.toString();
            selection.modify('move', 'forward', 'character');
            var wordInput = end+start;

            console.log(wordInput);
        }
    });
</script>
</body>

Expected Working

Let's suppose a textarea with text: 'Hello World'

When i click anywhere in 'Hello' it should print 'Hello' not the whole textarea value. Similarly for 'World' and so on.

Error in IE

SCRIPT438: Object doesn't support property or method 'modify'

Can anyone help me please? Thanks!

This code could help you, i guess.

 const getTheWord = (selectionStart, value) => { let arr = value.split(" "); let sum = 0 for (let i = 0; i < arr.length; i++) { sum += arr[i].length + 1 if (sum > selectionStart) return arr[i] } } const myArea = document.getElementById("myArea") myArea.value = "Hello world!" myArea.onclick = (e) => { let i = e.currentTarget.selectionStart console.log(getTheWord(i, myArea.value)) }
 <textarea id="myArea"></textarea>

No need to split all the text. This may lead to bad performance, because we do not know the length of text.

Give this a try:

function isSpace(character: string) {
  return /\s/.test(character);
}

export function getSelectedWord(
  selectionStart: number,
  value: string
): string | null {
  let start: number = selectionStart;
  let end: number = selectionStart;
  while (start - 1 >= 0 && !isSpace(value[start - 1]!)) {
    --start;
  }
  while (end + 1 < value.length && !isSpace(value[end + 1]!)) {
    ++end;
  }
  const word = value.slice(start, end + 1);
  return word || null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM