Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

80
Views
Count the capitals in the word javascript

) I am trying to solve one problem with this statement :

Write a function called howManyCaps which counts the capitals in the word,it then returns a sentence saying how which letters are capital and how many capitals there are in total.

This is my function

function howManyCaps(str) {
  var count = 0;
  for (i = 0; i < str.length; i++) {
    if (str[i] == str[i].toUpperCase()) {
      console.log(true);
      count++;
    } else {
      false;
    }
  }
  return count;
}

but in console if try with something like str=" How many Caps" y see a value of 5 instead of 2. Any suggestions? Thanks

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

The simplest way is [O(N)]:

function howManyCaps(str) {
    let upper = 0;
    for (let i = 0; i < str.length; i++) {
        if (str[i] >= 'A' && str[i] <= 'Z') upper++;
    }
    return upper;
};

howManyCaps(' How many Caps');

Some people are saying don't use spaced or account for spaces, but that also is not a good strategy because it will also break for special characters.

about 4 years ago · Juan Pablo Isaza Report

0

If regular expressions are available to you, I would suggest the following:

function howManyCaps(str) {
    return str.length - str.replace(/[A-Z]+/g, "").length;
}

var str = " How many Caps";
console.log("Input has " + howManyCaps(str) + " capital letters.");

The idea is to compare the length of the original input against the length of the input with all capital letters removed.

about 4 years ago · Juan Pablo Isaza Report

0

The better way is to use regex Below is the code

function howManyCaps(str) {
    return str.replace(/[^A-Z]/g, '').length;
}
console.log(howManyCaps(" How many Caps"))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!