简体   繁体   中英

Extracting capital letters ( English ) | Preferred method

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?

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.

正则表达式方法是迄今为止最简单和最有效的方法,因为它只是一个步骤而不是一个大循环。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM