I have the following code - All it does it grabs the value in a text box, performs regex on the string and then counts how many asterisks are in the string value:
var textBoxValue = $(textbox).val();
function countHowManyWildCards(stringToSearch) {
var regex = new RegExp(/\*/g);
var count = stringToSearch.toString().match(regex).length;
return count;
}
if (countHowManyWildCards(textBoxValue) > 1) {
//Other code
}
The code seems to work, but there is an error appearing on:
stringToSearch.toString().match(regex).length;
The error states:
Unable to get property 'length' of undefined or null reference
But I am unclear why the code works, but I still have this error? Can someone fill me in on why this happening?
Since match
is failing and not returning any array as a result calling .length
on it will throw that error.
To fix this you can use:
var count = (stringToSearch.match(regex) || []).length;
to take care of the case when match
fails. || []
will return an empty array when match fails and [].length
will get you 0
.
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