I have an input field with comma separated values. I want to get the text between commas so that I can add a sug开发者_如何学运维gestion for each element. I found that I can get the cursor position using the value of the first child, how do I get only the text between commas?
Edit: split will get value of an array, but I wish to know which word my cursor is on (between the commas). firstChild.nodevalue gives me the caret position. I would like the word at the caret position. Example: apple, orange, banana ... if my cursor was between the o and the range, it might give the suggestion orange, oranges, etc. If I somehow can get a function to return "orange" if my cursor is somewhere on the word, then I can compare it to a suggestion array.
This should do the trick...
var pos = 11; // use w/e you need to get the position.
var value = "apple, orange, banana";
var array = value.split(',');
var item = null;
var current_length = 0;
for(var i=0;i<array.length;i++) {
current_length += array[i].length;
if(pos < (current_length + i)) {
item = array[i].replace(/\s/ig, "");
break;
}
}
alert(item) // -> "orange"
Or without using split:
var pos = 11; // use w/e you need to get the position.
var value = "apple, orange, banana";
var item = '';
var len = value.length;
var pointer=pos;
while (true) { var char=value.substr(pointer,1); if (pointer-->=0 && char!=',') item = char + item; else break }
pointer=pos+1;
while (true) { var char=value.substr(pointer,1); if (pointer++<len && char!=',') item += char; else break}
alert(item) // -> "orange"
精彩评论