title: Get current word on caret position
body: <p>How can I get a word in textarrea by its current caret position?</p>
  
  <p>I tried something like this, however this returns just the words first letter upto the character at caret position. For example:</p>
  
  <p>if the cursor is between <em>fo</em> and <em>o</em> it returns <code>fo</code> and not <code>foo</code> as excpected.</p>
  
  <p>Fo<code>|</code>o bar is not equal to bar foo. => <code>Fo</code> expects <code>Foo</code></p>
  
  <p>Foo bar is not equ<code>|</code>al to bar foo. => <code>equ</code> expects  <code>equal</code>.</p>
  
  <p>Here's what I've done so far:</p>
  
  <pre><code>function getCaretPosition(ctrl) {
      var start, end;
      if (ctrl.setSelectionRange) {
          start = ctrl.selectionStart;
          end = ctrl.selectionEnd;
      } else if (document.selection &amp;&amp; document.selection.createRange) {
          var range = document.selection.createRange();
          start = 0 - range.duplicate().moveStart('character', -100000);
          end = start + range.text.length;
      }
      return {
          start: start,
          end: end
      }
  }
  
  $("textarea").keyup(function () {
      var caret = getCaretPosition(this);
  
      var result = /\S+$/.exec(this.value.slice(0, caret.end));
      var lastWord = result ? result[0] : null;
      alert(lastWord);
  });
  </code></pre>
  
  <p><a href="http://fiddle.jshell.net/gANLv/" rel="noreferrer">http://fiddle.jshell.net/gANLv/</a></p>