Home > Back-end >  how can I Create a function (countMs) that takes a string text and returns the number of letters
how can I Create a function (countMs) that takes a string text and returns the number of letters

Time:07-26

I need to solve this problem Create a function (countMs) that takes a string text and returns the number of letters 'm' in it (both uppercase and lowercase). Hint 1 .Create a variable count .Create a for of loop where you will iterate over each character of text At every iteration check whether the current character is 'm' or 'M': if it's true, increase the count by 1.

CodePudding user response:

Another approach would be to try it with String.prototype.match.

const str = "asd9089m1mmgrfsmbidjvmMmMmmamsdf1mr38jfMMmadfafvaMMmamsdmamas134m3mfMMmeasfmasmfamMmasmdm";
// Matches "m"
// i flag = case insensitive
// g flag = global, do not exit after the first match is found.
const totalMs = str.match(/m/ig).length;

console.log({ totalMs });

Otherwise do as per the Hint, which is to iterate each character. A string is basically an array of character, and you can use loop iteration to count if the character matches M or m.

CodePudding user response:

I get the feeling im doing someone's homework for them :)

function countMs(input) {
    let count = 0;
    for(let i = 0; i < input.length; i  ) {
        let c = input.charAt(i);
        if(c === 'M' || c === 'm') count  ;
    }
    return count;

}
  • Related