How to get line under cursor in input field with JavaScript
Came up with a small piece. I split the string by the cursor position and got the last characters from the first substring and the first from the second.
var value = $(el).val()
var split = el.selectionStart
var a = value.substring(0, split).match(/[A-Za-z]*$/)[0]
var b = value.substring(split).match(/^[A-Za-z]*/)[0]
console.log(a + b)
source to share
function getWord (str, curPos) {
var startIndex = (function _this (pos) {
if (!str.substring(pos, pos + 1).match(/[A-Za-z]/)) {
return pos + 1;
} else if (pos === 0) {
return 0;
} else {
return _this(pos - 1);
}
})(curPos - 1);
var endIndex = (function _this (pos) {
if (!str.substring(pos, pos + 1).match(/[A-Za-z]/) || pos === str.length) {
return pos;
} else {
return _this(pos + 1);
}
})(curPos + 1);
return str.substring(startIndex, endIndex);
}
See a working example here: http://jsfiddle.net/paulbruno/8PR9H/
Here's what's going on. getWord
It takes the input string, str
and the current cursor position curPos
. It then uses two recursive anonymous functions to insert each path into the string until it hits the beginning and end of the string. Technically they are called "Funciton Named Expressions" ( see here ) and allow you to recursively call a function even if you don't want to use it and want to store the function object for later use. Then, given those two indices, getWord
it uses the method again substring
to pass the word from the original str
.
source to share
The following works by looking for the first space character to the left and right of the starting position and returns the string in between. It considers any sequential character string denoted by spaces and will work even if the input is alphanumeric:
function myGetWord(aString,aPos){
Nstr = aString.length;
var start = aPos;
var end = aPos;
while (start>0 && aString[start]!=" ")
start--;
while (end<Nstr && aString[end]!=" ")
end++;
return aString.substring(start,end);
}
source to share
Try this: http://jsfiddle.net/fYkEB/
var el=document.getElementById('el');
var run=document.getElementById('run');
function findWord(str,pos){
var words=str.split(' ');
var offset=0;
var i;
for(i=0;i<words.length;i++){
offset+=words[i].length+1;
if (offset>pos) break;
}
return words[i];
}
run.onclick=function(){
run.value='Word at cursor: '+findWord(el.value,el.selectionStart);
};
source to share