Skip to content

Instantly share code, notes, and snippets.

@juliocesar
Created October 7, 2009 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliocesar/203610 to your computer and use it in GitHub Desktop.
Save juliocesar/203610 to your computer and use it in GitHub Desktop.
(function($) {
String.prototype.substrUntil = function(index, until, backwards) {
var string = [];
var regex = new RegExp(until, 'ig');
if (backwards) index--; // reverse the caret direction, pretty much
while(this[index]) {
if (regex.test(this[index])) break;
if (backwards) {
string.unshift(this[index]);
index--;
} else {
string.push(this[index]);
index++;
}
}
return string.join('');
}
$.fn.caretPos = function(element) {
// http://www.webdeveloper.com/forum/showthread.php?t=74982
// and many, many other references
var pos;
if (document.selection) {
var sel = document.selection.createRange();
sel.moveStart('character', this.get(0).value.length);
pos = sel.text.length;
} else {
pos = this.get(0).selectionStart;
}
return pos;
}
$.wordAtCaret = function(element) {
var value = $(element).val();
var index = $(element).caretPos();
var forward = value.substrUntil(index, ' ');
var backward = value.substrUntil(index, ' ', true);
return backward + forward;
}
$.fn.wordAtCaret = function() { return $.wordAtCaret(this.get(0)) }
})(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment