Created
October 7, 2009 00:39
-
-
Save juliocesar/203610 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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