Select closest word to cursor in textarea (like ctrl+D in sublime text)
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
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