Question

Using JS or jQuery I'd like to grab the whole word before the cursor. That means that if the cursor is between a certain word, than it grabs the whole word before it. For instance in the string:

This is a lame sentence.

If my cursor was between n and t in sentence it would select lame. If my cursor was in between or right before is it would grab This.

Here is what I've tried:

function getCaret(el) {
    return el.selectionStart;
  }

window.onload = function () {
  var textarea = document.getElementById('content'),
      status = document.getElementById('status');
  
  textarea.onmouseup = textarea.onkeyup = function () {
    status.innerHTML = getCaret(textarea);
  
    var char = $('#content').val().split('');
    var before = char.slice(0, getCaret(textarea)); 
    words = before.join('').split(' ');  
    var word = words.pop()
    wordBeforeCursor.innerHTML = word;

  };
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="status">Move the caret on the text:</div>
<textarea id = 'content'>
Here's a bunch of words
</textarea>
<div id="wordBeforeCursor"></div>

FIDDLE

Was it helpful?

Solution

Add these lines in your code,

last=words.length-1;
wordBeforeCursor.innerHTML = words[last] ? words[last] :'';

after var word = words.pop();

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top