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?
match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array. Syntax: string.match(regExp)
JavaScript String match() The match() method returns null if no match is found.
Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .
Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With