2011-04-06 78 views
5

我想算一個pre元素的行#和我使用這樣的:JavaScript的比賽()錯誤

var numlines = $('#mypreelement').text().match(/\n\r?/g).length + 1; 

它的工作原理,但在某些情況下,我得到一個錯誤

Error: $('#mypreelement').text().match(/\n\r?/g) is null

這隻發生在某些頁面,但這些頁面沒有任何不同之處,除了內容當然...

爲什麼?

+1

從這個問題的答案(http://stackoverflow.com/questions/2035910/how-to-get-the- textarea中的行數)具有用於匹配跨瀏覽器硬返回的正則表達式。 – Mottie 2011-04-06 03:17:09

回答

7

這意味着它不能匹配任何一個,並且null沒有length屬性。

那麼試試這個...

if (var lines = $('#mypreelement').text().match(/\n\r?/g) != null) { 
    var linesLength = lines.length + 1; 
} 
2

MDC RegExp Match

If the regular expression includes the g flag, the method returns an Array containing all matches. If there were no matches, the method returns null.