Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  56] [ 1]  / answers: 1 / hits: 19122  / 9 Years ago, fri, august 7, 2015, 12:00:00

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?


More From » jquery

 Answers
25

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.


[#65500] Wednesday, August 5, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
miles

Total Points: 256
Total Questions: 111
Total Answers: 104

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
;