<p>How do you get the caret position in a <code>&lt;textarea&gt;</code> using JavaScript?</p>

<p>For example: <code>This is| a text</code></p>

<p>This should return <code>7</code>.</p>

<p>How would you get it to return the strings surrounding the cursor / selection?</p>

<p>E.g.: <code>'This is', '', ' a text'</code>.</p>

<p>If the word “is” is highlighted, then it would return <code>'This ', 'is', ' a text'</code>.</p>

With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
```
```
function getCaret(node) {
  if (node.selectionStart) {
    return node.selectionStart;
  } else if (!document.selection) {
    return 0;
  }

  var c = "\001",
      sel = document.selection.createRange(),
      dul = sel.duplicate(),
      len = 0;

  dul.moveToElementText(node);
  sel.text = c;
  len = dul.text.indexOf(c);
  sel.moveStart('character',-1);
  sel.text = "";
  return len;
}
```
```
(
complete code here
)
I also recommend you to check the jQuery
FieldSelection
Plugin, it allows you to do that and much more...
Edit:
I actually re-implemented the above code:
```
```
function getCaret(el) { 
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
        rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    return rc.text.length; 
  }  
  return 0; 
}
```
```
Check an example
here
.