Getting length of array returned by a regex? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Getting length of array returned by a regex?

Hello I am practicing JavaScript and I got in a little problem I can’t figure out: I’m trying to get an array containing all occurrences from a regex in JavaScript and I’m doing something like this: var str = “This IS a trY”; var pattern = /[A-Z]/g; var matches = str.match(pattern); And till now it all works because if I do console.log(matches) it will print out something like this ( T, I, S, Y ) Just like it usually do with arrays, so I am assuming that in this case the match method is returning an array with all occurrences from the regex. The problem is that I would like to get the length of this array, but if I do matches.length as we usually do for an array I will get an error... so should I assume that the method is not actually returning an array? Is there a better way to do what I’m trying to do?

19th Jan 2019, 4:10 PM
Sekiro
Sekiro - avatar
4 Answers
+ 3
Sekiro I find your follow question somewhat confusing, and I apologize for that. I sometimes use w3school as a reference source, it may help be of some help to you. https://www.w3schools.com/jsref/jsref_obj_regexp.asp https://code.sololearn.com/WrZG4qY1D6E8/#js
20th Jan 2019, 2:51 AM
ODLNT
ODLNT - avatar
+ 3
Sekiro You can use the array method isArray() to check if an object is an array or not. /[A-Z]/g does return an array of the matches found, so you can use the property length to get the number of an element within an array. var str = "This IS a tyY"; var pattern = /[A-Z]/g; var matches = str.match(pattern); console.log(Array.isArray(matches)); matches.forEach(item=>console.log(item)); console.log(matches.length);
20th Jan 2019, 12:13 AM
ODLNT
ODLNT - avatar
+ 1
Thank you ODLNT for your answer! I tried that and it works, but only when there is an occurence of the given pattern, if nothing is found I get an error: null reference cannot evaluate forEach, or something alike.. Is there no way to get an array with all occurences of a given pattern from a regex? And also I’d like it to includes duplicates as well... for example for the string: ThT huO find all capital letters and get an array that will result like this: [T, T, O]
20th Jan 2019, 1:19 AM
Sekiro
Sekiro - avatar
+ 1
Thank you ODLNT ! I solved my problem, after reading your code I realized that I was trying to get the results of the match without checking if there actually was at least one match, so I was getting an error! I apologize for my messy questions 😅 Thanks again!
20th Jan 2019, 3:46 AM
Sekiro
Sekiro - avatar