Skip to content

Instantly share code, notes, and snippets.

@ddeveloperr
Created April 1, 2015 10:32
Show Gist options
  • Select an option

  • Save ddeveloperr/1f5e31509cda8469c972 to your computer and use it in GitHub Desktop.

Select an option

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
/*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