开发者

How to get word under current cursor position in textarea in flex 4

开发者 https://www.devze.com 2023-04-09 17:17 出处:网络
I\'m using flex4 for creating an editor. There I need to get word开发者_如何学运维 under current cursor position. say for example, this is the text in textarea, \"Hi, this is a sample\" and cursor und

I'm using flex4 for creating an editor. There I need to get word开发者_如何学运维 under current cursor position. say for example, this is the text in textarea, "Hi, this is a sample" and cursor under "this" word. If I click a button, then this "this" word must be returned. All this I need to implement in flex4 and actionscript3. Please provide any kind of suggestion or help.


Take a look at TextField.caretIndex. It is the index position of the cursor in the textfield. Then you need to extract the current word using that position. One way is to look for spaces in both directions but I am sure there is some fancy Regular Expression out there that can do it for you using the caret index.


I needed such a function for code hinting, this approach works nicely:

public function currentWord(ta:RichEditableText):String
{
    var wordBegin:int = ta.selectionAnchorPosition;
    var wordEnd:int = ta.selectionAnchorPosition;
    // while the previous char is a word character... let's find out where the word starts
    while (ta.text.charAt(wordBegin-1).search(/\w+/) > -1 && wordBegin > 0 ) { wordBegin--; }
    // while the next char is a word character... let's find out where the word ends
    while (ta.text.charAt(wordEnd).search(/\w+/) > -1 && wordEnd > 0 ) { wordEnd++; }
    return ta.text.substring(wordBegin, wordEnd);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消