2
 function onlyCapitalLetters (str)  

 { 

let newStr = "";

for (let i = 0; i < str.length; i ++) {
    if (str[i].includes("ABCDEFGHIJKLMNOPQRSTUVWXYZ")) {
        newStr += str[i];
       
    }
}
return newStr;
}

onlyCapitalLetters("AMazing"); // should get AM

Hi, I'm trying to write a function, that will return a new string with only capital letters. When I try to run this function, I don't see any output. Please help!!!

Jojo
  • 71
  • 1
  • 2
  • 5

4 Answers4

5

In practice, you would probably use a regex approach here:

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

console.log(onlyCapitalLetters("AMazing")); // should get AM
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

Include requires everything within to be included in the provided string. Use regex instead

function onlyCapitalLetters (str) { 
  let newStr = "";

  for (let i = 0; i < str.length; i++) {
      if (str[i].match(/[A-Z]/)) {
          newStr += str[i];
      }
   }
   return newStr;
}


console.log(onlyCapitalLetters("AMazing")); // should get AM

You could one line this function like this

const capital = (str) => str.split('').filter(a => a.match(/[A-Z]/)).join('')

console.log(capital("AMazinG"))
Advaith
  • 2,490
  • 3
  • 21
  • 36
0

The string of letters (uppercaseLetters) should include the current letter (str[i]), and not the other way around:

function onlyCapitalLetters(str) {
  let newStr = "";
  
  const uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  for (let i = 0; i < str.length; i++) {
    if (uppercaseLetters.includes(str[i])) {
      newStr += str[i];
    }
  }
  
  return newStr;
}

console.log(onlyCapitalLetters("AMazing")); // should get AM

A better option would be to use String.match() to find all uppercase letters. The match method returns an array of letters found, or null if none found, so we'll need to use an empty array as a fallback. Join the resulting array with an empty string.

function onlyCapitalLetters(str) {
  return (str.match(/[A-Z]/g) || []).join('');
}

console.log(onlyCapitalLetters("AMazing")); // should get AM
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

String.Includes() checks for all the characters in the string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

You can also use ASCII code for the Characters to verify if it is a capital letter.

function onlyCapitalLetters (str) { 
 let newStr = "";

    for (let i = 0; i < str.length; i++) {
      if (str[i].charCodeAt(0) >= 65 && str[i].charCodeAt(0) <= 90) {
          newStr += str[i];
       }
    }
  return newStr;
}

console.log(onlyCapitalLetters("AMazing"));
Sasi Kumar M
  • 2,440
  • 1
  • 23
  • 23