-
Notifications
You must be signed in to change notification settings - Fork 0
/
3.3-Bean_Counting.js
36 lines (28 loc) · 1.35 KB
/
3.3-Bean_Counting.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//EXERCISE
/* You can get the Nth character, or letter, from a string by writing "string"[N]. The returned value will be a string containing only one character (for example, "b").
The first character has position 0, which causes the last one to be found at position string.length - 1.
In other words, a two-character string has length 2, and its characters have positions 0 and 1.
Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters there are in the string.
Next, write a function called countChar that behaves like countBs, except it takes a second argument that indicates
the character that is to be counted (rather than counting only uppercase “B” characters). Rewrite countBs to make use of this new function. */
//With Reg Exp
function countChar(str, char) {
const regex = new RegExp(`${char}`, 'g');
const found = str.match(regex);
if (found && char) return found.length;
else return 'Wrong input';
}
function countBs(str) {
return countChar(str, 'B');
}
//With a foor loop
function countChar(str, char) {
var count = 0;
for (let i = 0; i < str.length; i++) if (str[i] == char) count++;
return count;
}
function countBs(str) {
return countChar(str, 'B');
}
console.log(countBs('BaaasB')); //2
console.log(countChar('aaaaaaaBBBBBBBaaBBBBBBB', 'B')); //14