Reputation: 111062
I can get the actual position of the cursor in an input field. How can I get the whole word on this position. For example my input has the following text: Hello World
, and the cursor is at position 2. How could I get Hello
?
Upvotes: 4
Views: 1698
Reputation: 2368
The following works by looking for the first space character on the left and on the right of the starting position and returns the string in between. It considers any consecutive string of characters delineated 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);
}
Upvotes: 1
Reputation: 1906
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 working example here: http://jsfiddle.net/paulbruno/8PR9H/
Here's what's happening. getWord
takes the input string, str
, and the cursor's current position, curPos
. It then uses two recursive anonymous functions to push each way in the string, until they hit the start and end of the string. Technically, they're called "Named Funciton Expressions" (see here), and allow you to recursively call a function, even if you don't want to save the function object for later use. Then, after getting these two indexes, getWord
uses the substring
method again, to pass back the word from the original str
.
Upvotes: 1
Reputation: 42654
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);
};
Upvotes: 0
Reputation: 111062
Came up with small piece. I split the string at the cursor position and get the last chars from the first substring and the first of the second one.
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)
Upvotes: 3