5

I'm trying to count # of lines of a pre element and I'm using this:

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

it works, but in some situations I get a error

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

this only happens on certain pages, but these pages don't have anything different from the ones on which it works, besides content of course...

Why?

Alex
  • 66,732
  • 177
  • 439
  • 641
  • 1
    The answer from this question (http://stackoverflow.com/questions/2035910/how-to-get-the-number-of-lines-in-a-textarea) has a regex for matching cross-browser hard returns. – Mottie Apr 06 '11 at 03:17

2 Answers2

7

That means it couldn't match any of them, and null does not have a length property.

So try this...

if (var lines = $('#mypreelement').text().match(/\n\r?/g) != null) {
   var linesLength = lines.length + 1;
}
alex
  • 479,566
  • 201
  • 878
  • 984
3

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.

epascarello
  • 204,599
  • 20
  • 195
  • 236