Can't get property length undefined or null reference

I have the following code, all it does is grab the value in the textbox, execute the regex on the string, and then count 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 works, but the error appears:

stringToSearch.toString().match(regex).length;

      

Mistake:

Can't get property length undefined or null reference

But I don't understand why the code is working, but I still have this error? Can anyone fill me in on why this is happening?

+3
javascript jquery regex


source to share


3 answers


Since it match

fails and does not return any array in the result, calling .length

will throw this error.

To fix this, you can use:



var count = (stringToSearch.match(regex) || []).length;

      

to take care of the case when it match

fails. || []

will return an empty array if the match fails and [].length

will get you 0

.

+5


source to share


Return value . match (regex) is equal null

if there is no match.



+1


source to share


stringToSearch.toString (). match (regex) will return null if stringToSearch does not contain any "*"

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics