Skip to content

Instantly share code, notes, and snippets.

@mimoo
Last active August 29, 2015 13:57
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 mimoo/9907534 to your computer and use it in GitHub Desktop.
Save mimoo/9907534 to your computer and use it in GitHub Desktop.
Select closest word to cursor in textarea (like ctrl+D in sublime text)
var textarea = textarea
// detect dots and comas
function trimtrim (truc) {
truc = $.trim(truc)
truc = truc.replace(/\./, "");
truc = truc.replace(/\,/, "");
truc = truc.replace(/\;/, "");
return truc
}
// select closest word
function selectClosestWord(){
// selection
var start = textarea.prop("selectionStart")
var end = textarea.prop("selectionEnd")
// is any word highlighted?
if(start == end){
var textarea_text = textarea.val()
var word = ""
// left side
if(start != 0){
while(trimtrim(word) == word){
start = start - 1
word = textarea_text.substr(start, end - start);
if(start == 0)
break
}
if(start != 0)
start++
word = trimtrim(word)
}
// right side
if(end < textarea_text.length){
while(trimtrim(word) == word){
end = end + 1
console.log(end)
word = textarea_text.substr(start, end - start);
if(end > textarea_text.length)
break
}
if(end <= textarea_text.length)
end--;
word = trimtrim(word)
}
textarea.prop('selectionStart', start)
textarea.prop('selectionEnd', end)
textarea.focus()
return word
}
}
// CTRL + D
$(document).bind('keydown', function(e) {
if(e.ctrlKey && (e.which == 68)) {
e.preventDefault()
selectClosestWord()
return false
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment