I am counting how many times strings contain an aa appears in an array. I dont think there is something wrong with my code. like below
const regex_aa = /aa[^(aa)]?$/s;
let arr = [];
const sstr = ['aa', 'aaaa', 'cc', 'ccc', 'bbb', 'bbaa'];
sstr.filter(e => {
if (regex_aa.test(e)) {
arr.push(e);
}
});
console.log(arr.length);
So the number is 3 which is correct.
However, the next job is to count how many times appears, then it looks like
const regex_aa = /aa[^(aa)]?$/s;
const regex_bb = /bb[^(aa)]?$/s;
let arr1 = [];
let arr2 = [];
const sstr = ['aa', 'aaaa', 'cc', 'ccc', 'bbb', 'bbaa'];
sstr.filter(e => {
if (regex_aa.test(e)) {
arr1.push(e);
}
if (regex_bb.test(e)) {
arr2.push(e);
}
});
console.log(arr1.length, arr2.length);
so each time if I want to find the number of a new string, I have to create a new let, I found this way is a bit clumsy. Is there a better solution for counting strings? Thanks
filter()you shouldn't push into an array, you should just return the comparison result.filter()will return the new array.regex_jsshould beregex_aa. But your regex doesn't make much sense. If you just want to know if the string containsaa, it should just he/aa/bboccurs twice in thesstr, so shouldn't its result be2, not1?[^(aa)]?doesn't mean whatever you think it does.[^(aa)]means to match a single character that isn't(,aor). It makes no sense to repeat a character inside[].