2010-06-30 41 views

回答

6

一個簡單的方法是隻循環:

var caretPos = 53, // however you get it 
    start, end 
; 

for (start = caretPos; start >= 0 && myString[start] != "\n"; --start); 
for (end = caretPos; end < myString.length && myString[end] != "\n"; ++end); 

var line = myString.substring(start + 1, end - 1); 
+0

非常感謝 – 2010-07-01 00:11:43

3

與nickf的答案,下面的例子(使用jQuery的)線路可能有點快,因爲它使用了(lastI|i)ndexOf

function current_line(textarea) { 
    var $ta = $(textarea), 
     pos = $ta.getSelection().start, // fieldselection jQuery plugin 
     taval = $ta.val(), 
     start = taval.lastIndexOf('\n', pos - 1) + 1, 
     end = taval.indexOf('\n', pos); 

    if (end == -1) { 
     end = taval.length; 
    } 

    return taval.substr(start, end - start); 
} 

這裏是on jFiddle

+0

在IE中無法正常工作 – andufo 2011-12-15 01:05:48

+0

感謝indexOf方法! – 2014-08-08 15:09:44