so I've actually came into this quation in a javascript tutorial by rithm school(which is very nice by far): Write a function called onlyCapitalLetters which accepts a string and returns a new string with only the capital letters passed to the string. this is the requested output:
onlyCapitalLetters("Amazing") // "A"
onlyCapitalLetters("nothing") // ""
onlyCapitalLetters("EVERYTHING") // "EVERYTHING"
thye've got this solution, but it's using this .charCodeAt() method which they haven't talked about before, and also seems pretty sophisticated. right now I am reading a lot of documentation related to it but still can't dig it.
before I've gine into their solution, Iv'e tried something else by myself, which was based about the things that were already introduce in this tutorial.
rithm school's solution:
function onlyCapitalLetters(str){
var newStr = '';
for(var i = 0; i < str.length; i++){
if(str[i].charCodeAt(0) < 91 && str[i].charCodeAt(0) > 64 ){
newStr += str[i];
}
}
return newStr;
}
my attempt:
function onlyCapitalLetters(string) {
var newString = '';
for(i=0;i<string.length;i++) {
if(string[i] === string[i].toUpperCase) {
} newString += string[i];
}
return newString;
}
although, when I've thrown an string as an argument, such as
onlyCapitalLetters('TbRnY OnUmT');
it gave me back the string as is, insted of a new, only uppercase string.
"TbRnY OnUmT"
is there a way, more in this simplified direction I've tried, to go for making this function happen? in addition, does anyone has some insights about this charCodeAt and their whole solution in general? This is my first post, so thank you for your help anyway!
so I've actually came into this quation in a javascript tutorial by rithm school(which is very nice by far): Write a function called onlyCapitalLetters which accepts a string and returns a new string with only the capital letters passed to the string. this is the requested output:
onlyCapitalLetters("Amazing") // "A"
onlyCapitalLetters("nothing") // ""
onlyCapitalLetters("EVERYTHING") // "EVERYTHING"
thye've got this solution, but it's using this .charCodeAt() method which they haven't talked about before, and also seems pretty sophisticated. right now I am reading a lot of documentation related to it but still can't dig it.
before I've gine into their solution, Iv'e tried something else by myself, which was based about the things that were already introduce in this tutorial.
rithm school's solution:
function onlyCapitalLetters(str){
var newStr = '';
for(var i = 0; i < str.length; i++){
if(str[i].charCodeAt(0) < 91 && str[i].charCodeAt(0) > 64 ){
newStr += str[i];
}
}
return newStr;
}
my attempt:
function onlyCapitalLetters(string) {
var newString = '';
for(i=0;i<string.length;i++) {
if(string[i] === string[i].toUpperCase) {
} newString += string[i];
}
return newString;
}
although, when I've thrown an string as an argument, such as
onlyCapitalLetters('TbRnY OnUmT');
it gave me back the string as is, insted of a new, only uppercase string.
"TbRnY OnUmT"
is there a way, more in this simplified direction I've tried, to go for making this function happen? in addition, does anyone has some insights about this charCodeAt and their whole solution in general? This is my first post, so thank you for your help anyway!
Share Improve this question edited Jan 16, 2019 at 17:54 Andy 63.6k13 gold badges71 silver badges98 bronze badges asked Jan 16, 2019 at 17:46 blabla 811 silver badge7 bronze badges 4-
should be
if(string[i] === string[i].toUpperCase())
— the()
is important – Pointy Commented Jan 16, 2019 at 17:47 - also I think your solution is better :) – Pointy Commented Jan 16, 2019 at 17:48
-
1
Also the placement of your closing brackets
}
is wrong. – Patrick Roberts Commented Jan 16, 2019 at 17:48 - Should it also work for strings like "abc@#" (with special characters) or it is not the case? – Adrian Pop Commented Jan 16, 2019 at 18:19
6 Answers
Reset to default 4Regarding your attempt, you were almost there! Your mistakes were:
toUpperCase
should betoUpperCase()
, since it's a method that must be applied- remove the empty
{}
block; this will prevent the following statement to be executed only when theif
statement is true; you can also move the concatenation inside the{}
block
The modified version is below:
function onlyCapital(string) {
var newString = '';
for (i = 0; i < string.length; i++) {
if (string[i] === string[i].toUpperCase())
newString += string[i];
}
return newString;
}
console.log(onlyCapital("nothing"));
console.log(onlyCapital("TesT"));
console.log(onlyCapital("TbRnY OnUmT"));
However, this won't work for a string like "abc#@", since applying toUpperCase()
to a special character, will return the same character, and the if statement will be true, resulting in a concatenation. That's why they used charCodeAt(0)
. This function in javascript returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. For ASCII characters, it means it will return a number between 0 and 127. What can we do with this number? We can pare it with other numbers (take a look at the ASCII table here) and test if it is a valid letter or not. Looking in that table, we can see that:
- A is 65
- Z is 90
- a is 97
- z is 122
With the above information, we can create another function named isLetter
that will tests if a given character is a valid letter or not. How? Testing if the code of our character is between A and Z or a and z. But, since we don't need the smaller letters anyway, we can just test for [A, Z]. Combining this with the code above, we will have this:
function isUppercaseLetter(c) {
return (c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90)
}
function onlyCapital(string) {
var newString = '';
for (i = 0; i < string.length; i++) {
if (isUppercaseLetter(string[i])) {
newString += string[i];
}
}
return newString;
}
console.log(onlyCapital("nothing"));
console.log(onlyCapital("EVERYTHING"));
console.log(onlyCapital("TbRnY OnUmT"));
console.log(onlyCapital("S@P#E!C#I?A;L"));
Bonus:
I'll do it using the filter
lambda function. First, we convert the string to a char array and then keep only the characters that are uppercase. You can learn more about how reduce works here. Another method using functionals would be with reduce
. You can take a look how reduce works here. Basically I use split
to turn the string into a char array, then for each character, I either add it to the partial result or I just keep the partial result. In the end, I should have my string.
function isUppercaseLetter(c) {
return (c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90);
}
function onlyCapitalWithFilter(s) {
return s.split('').filter(c => isUppercaseLetter(c)).join('');
}
function onlyCapitalWithReduce(s) {
return s.split('').reduce((a, c) => isUppercaseLetter(c) ? a + c : a, '');
}
console.log(onlyCapitalWithFilter("nothing"));
console.log(onlyCapitalWithFilter("TesT"));
console.log(onlyCapitalWithFilter("TbRnY OnUmT"));
console.log(onlyCapitalWithFilter("S@P#E!C#I?A;L"));
console.log(onlyCapitalWithReduce("nothing"));
console.log(onlyCapitalWithReduce("TesT"));
console.log(onlyCapitalWithReduce("TbRnY OnUmT"));
console.log(onlyCapitalWithReduce("S@P#E!C#I?A;L"));
I will do it using regex
.
/[A-Z]/g
matches all the capital letters.
join('')
convert matched characters array back to string.
function onlyCapitalLetters(input){
let op = input.match(/[A-Z]/g) || ''
if(op) op = op.join('')
console.log(op)
}
onlyCapitalLetters("Amazing") // "A"
onlyCapitalLetters("nothing") // ""
onlyCapitalLetters("EVERYTHING")
onlyCapitalLetters('TbRnY OnUmT');
function onlyCapitalLetters(string) {
// prime the function response.
let response = "";
// match all groups of uppercase letters.
let result = string.match(/([A-Z]+)/g);
// check for matches.
if( result != null && result.length ) {
// remove first element of match result (which returns the original string.
result.unshift();
// join the array into a string with an empty "separator".
response = result.join('');
}
console.log(response);
return response;
}
onlyCapitalLetters("Amazing") // "A"
onlyCapitalLetters("nothing") // ""
onlyCapitalLetters("EVERYTHING") // "EVERYTHING"
onlyCapitalLetters('TbRnY OnUmT'); // "TRYOUT"
To fix you code, use toUpperCase() including the parenthesis and concatenate the string inside the if statement:
if (string[i] === string[i].toUpperCase()) {
newString += string[i];
}
Note that as @CodeManiac points out, this function will not remove special characters from the string. Using nothing@#
will return @#
For example
function onlyCapitalLetters(string) {
var newString = '';
for (let i = 0; i < string.length; i++) {
if (string[i] === string[i].toUpperCase()) {
newString += string[i];
}
}
return newString;
}
console.log(onlyCapitalLetters('TbRnY OnUmT'));
console.log(onlyCapitalLetters('nothing@#'));
Another option could be to replace not an uppercase character or a whitespace character with an empty string:
function onlyCapitalLetters(string) {
return string.replace(/[^A-Z\s]+/g, '');
}
console.log(onlyCapitalLetters('TbRnY OnUmT'));
Another Option is using array destructuring
as function parameter.
const onlyCapitalLetters = ([...myarr] = e) => myarr.filter(el => el === el.toUpperCase()).join('');
console.log(onlyCapitalLetters("Amazing"));
console.log(onlyCapitalLetters("nothing"));
console.log(onlyCapitalLetters("EVERYTHING"));
Here is a pact solution
var string = "ABCefgGHaI";
First of all replace all chars other than alphabets
string.replace(/[^a-z]/gi, '')
(string.split('').filter((item)=>{return item == item.toUpperCase()})).join("")
You can do this by splitting the word and filter only those which are in uppercase and rejoin them :)