开发者

javascript match() error

开发者 https://www.devze.com 2023-02-22 03:17 出处:网络
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;

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开发者_Python百科 certain pages, but these pages don't have anything different from the ones on which it works, besides content of course...

Why?


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;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消