Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract only Capital letters from a string - javascript [duplicate]

 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!!!

like image 295
Jojo Avatar asked May 18 '26 19:05

Jojo


2 Answers

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
like image 100
Tim Biegeleisen Avatar answered May 20 '26 09:05

Tim Biegeleisen


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"))
like image 30
Advaith Avatar answered May 20 '26 09:05

Advaith