Reputation:
Given a string of text
var string1 = 'IAmNotFoo';
How do you extract just the capital letters?
'IANF'
Here are some methods per links below:
function isUpperCase1(aCharacter) {
if ( ch == ch.toUpperCase() ) {
return true;
}
return false;
}
function isUpperCase2( aCharacter ) {
return ( aCharacter >= 'A' ) && ( aCharacter <= 'Z' );
}
var string1 = 'IAmNotFoo',
string2 = '',
i = 0,
ch = '';
while ( i <= string1.length ) {
ch = string1.charAt( i );
if (!isNaN( ch * 1 ) ) {
alert('character is numeric');
}
else if ( isUpperCase2() ) { // or isUpperCase1
string2 += ch;
}
i++;
}
or simply ( per comment below ):
var upper = str.replace(/[^A-Z]/g, '');
SO Related
Finding uppercase characters within a string
How can I test if a letter in a string is uppercase or lowercase using JavaScript?
Upvotes: 1
Views: 1559
Reputation: 1443
I like working with numbers so I would prefer converting to integers and checking the ascii range. You can see this chart here www.ascii-code.com.
All capital letters have a separate ascii code from their lower case counterparts.
do something like this
String str = "IAmNoFoo";
returnCaps(str);
Public static String returnCaps(String, str)
{
for (int i = 0; i < str.length; i++)
{
int letter = str.convertToInt(charAt(i));
if (letter >= 65 || letter <= 90)
return str.substring.charAt(i);
else
return "No Capital Letters Found"
}
}
You might need to set the loop check to i <= str.length
This will check to see if the character at each index of the string is a captial or not. I think it is easiest to think mathematically.
With a little tweaking you could very easily make this into a recursive method.
Upvotes: 1
Reputation: 324780
The regex method is by far the simplest and most efficient, since it is just a single step as opposed to a big loop.
Upvotes: 1