Created
April 1, 2015 10:32
-
-
Save ddeveloperr/1f5e31509cda8469c972 to your computer and use it in GitHub Desktop.
Write a function that takes a string as its argument and count assign char
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*Write a function countBs that takes a string as its only argument and returns a number that | |
| indicates how many uppercase “B” characters are in the string. | |
| Second, 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.*/ | |
| var countBs, countChar; | |
| countBs = function(str) { | |
| return countChar(str, "B"); | |
| }; | |
| countChar = function(str, chr) { | |
| var counter, i, r; | |
| counter = 0; | |
| for (i = 0, r = str.length; 0 <= r ? i < r : i > r; 0 <= r ? i++ : i--) { | |
| if (str.charAt(i) === chr) { | |
| counter++; | |
| } | |
| } | |
| return counter; | |
| }; | |
| console.log(countBs("BiBBleBiBBleDuBBle")); | |
| // → 8 | |
| console.log(countChar("BiBBleBiBBleDuBBle", "l")); | |
| // → 3 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment