JavaScript - I get an error in Firebug
I am searching through a string trying to count the number of occurrences of @@ (two @ signs in a row). My code works well when the count is greater than 0, but I get an error in Firebug when the occurrence is zero.
This throws an error:
var str = "This string has no at signs!";
var pcount = str.match(/@@/g).length;
alert(pcount);
var str = "This string has @@ one pair of signs!";
var pcount = str.match(/@@/g).length;
alert(pcount);
var str = "This @@ string has @@ two pairs of signs!";
var pcount = str.match(/@@/g).length;
alert(pcount);
The error I get in Firebug is:
str.match(/@@/g) is null
[Break On This Error] var pcount = str.match(/@@/g).length;
What I want is for pcount to be zero if no @@ is found.
Can you help?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ANSWER
I ended up using a combination of your answers. Thanks so much for your help!!!
var NewRows = getRowCount(ThisTextLen);
var Match = ThisText.match(/@@/g);
var ParagraphCount = 0;
if (Match != null) {
ParagraphCount = ThisT开发者_如何学JAVAext.match(/@@/g).length;
NewRows = NewRows + ParagraphCount;
}
Try:
var match = str.match(/@@/g);
var pcount = 0;
if (match != null) {
pcount = str.match(/@@/g).length;
}
alert(pcount);
You can write:
var pcount = (str.match(/@@/g) || []).length;
In case there is no match (the return value of str.match(/@@/g)
will be null
, which evaluates to false
), the length
property of the empty array will be accessed.
Try something like
var matched = str.match(/@@/g);
if(matched == null)
pcount = 0;
else
pcount = matched.length;
(or something more idiomatic like what Felix suggested, but this is the same idea)
Because no matches for /@@/, that is reason to return null object, so what you can do is
var str = "This string has two pairs of signs!";
var matches = str.match(/@@/gi);
var pcount = matches != null ? matches.length : 0;
alert(pcount);
this will work fine
var str = "This @@ string has @@ two pairs of signs!";
var pcount = 0;
if(str.match(/@@/g)!=null)
pcount =str.match(/@@/g).length;
alert(pcount);
精彩评论