2

is there a way to get a string under current cursor position inside a textarea
for example - click on lorem - console should be lorem
essentially, something like this:

  let a = previous space or line break from cursor position
  let b = next space or line break from cursor position
  console.log(text from a to b);

$('#ed').on('click', function(){
  //let a = previous space or line break from cursor position
  //let b = next space or line break from cursor position
  //console.log(text from a to b);
});
#ed{
display:block;
width:100%;
padding:9px;
height:50vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id='ed'>
lorem ipsum
https://google.com
</textarea>
qadenza
  • 9,025
  • 18
  • 73
  • 126

2 Answers2

1

I was able to do this using selectionStart as a key for the value of the textarea. This way when we embed this into an event listener on click, it will return the key of the text string within the textarea. We create a function that looks for a match of letters, if we have a match on the key where the cursor is placed, then we iterate backwards until there is no longer a letter, this gives us the beginning of the word. Then we reiterate forward until there is no match and push the values of the textArea.value[key] into an array, join this array to create a string of the characters that make up that word.

Also need a conditional to make sure we are within the length of the string start and end, less an error is thrown as the value will be null or undefined.

I used an event listener that listens for a click.

const textArea = document.getElementById('textArea')
const display = document.getElementById('display')

const getSelectedText = () => {
  let key = textArea.selectionStart;
  const word = [];
  const letters = /^[A-Za-z]+$/;
  if (key < textArea.value.length && key > 0) {
    while (textArea.value[key].match(letters)) {
      key--
      if (key < 1) {
        while (textArea.value[key].match(letters)) {
          word.push(textArea.value[key])
          key++
        }
      } else if (textArea.value[key].match(letters) === null) {
        key++
        while (textArea.value[key].match(letters)) {
          word.push(textArea.value[key]);
          key++
        }
      }
    }
  }
  return word.join('');
}

textArea.addEventListener('click', () => {
  display.innerHTML = `<b>Your selected text is:</b> <i>${getSelectedText()}</i>`
})
<textarea id='textArea' rows="7" cols="50">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</textarea>

<div id="display"></div>
dale landry
  • 7,831
  • 2
  • 16
  • 28
1

You are wellcome,

var borderChars = [' ', '\n', '\r', '\t']
$(function() {
    $('textarea').on('click', function() {
        var text = $(this).html();
        var start = $(this)[0].selectionStart;
        var end = $(this)[0].selectionEnd;
        while (start > 0) {
            if (borderChars.indexOf(text[start]) == -1) {
                --start;
            } else {
                break;
            }                        
        }
        ++start;
        while (end < text.length) {
            if (borderChars.indexOf(text[end]) == -1) {
                ++end;
            } else {
                break;
            }
        }
        var currentWord = text.substr(start, end - start);
        console.log(currentWord);
    });
});
Ceyhun
  • 1,354
  • 2
  • 10
  • 10