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!!!
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
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With