Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript match() error

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?

like image 691
Alex Avatar asked Apr 06 '11 02:04

Alex


People also ask

What is match function in JavaScript?

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)

What does match return if no match JS?

JavaScript String match() The match() method returns null if no match is found.

How do you match in regex?

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 "@" .

How do I check if a string is in regular expressions?

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.


1 Answers

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;
}
like image 96
alex Avatar answered Sep 22 '22 09:09

alex