Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get property 'length' of undefined or null reference

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?

like image 410
GIVE-ME-CHICKEN Avatar asked Feb 09 '23 09:02

GIVE-ME-CHICKEN


1 Answers

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.

like image 178
anubhava Avatar answered Feb 11 '23 21:02

anubhava