首页 > 解决方案 > How can I check if a string item within an array is all uppercase?

问题描述

I have an array called Symbols, it gets strings found by a regular expression pushed into it. I now need to sort through the array and find out if there is a string that has every letter capitalized in it. I have tried similar things in the classified function below everything has returned "false" thus far, even if there is an element that is just "AAAA"

let symbols = [];
let regr = RegExp(/{\$([^\$]+)\$}/, 'g')

function genToken(inStream){
    let array;
    let vrtStream = inStream.trim();
    console.log("Extracting meaningful symbols from string: ", vrtStream);

    while((array = regr.exec(vrtStream)) !== null){
        console.log(`Meaningful symbol: ${array[0]} found and assigned. Next starts at ${regr.lastIndex}.`)
        symbols.push(array)
    }
    if(symbols.length > 0){ 
        for(index = 0; index < symbols.length; index++){
            symbols[index].splice(0, 1);
            console.log(`${symbols[index].length} meaningful symbols currently indexed.`);
            console.log(symbols);
            }// end for
        return classify(symbols); 
        } else {
            console.log("no elements in array");
        }

    function classify(data, index){
        console.log("Classify called", symbols)
        //symbols is data

        symbols.forEach(function(item, index, array){
            if(item.toUpperCase == true){
                console.log(`${item} is upper`)
            } else {
                console.log('false');
            }
        })
        
    }    
}

标签: javascript

解决方案


If you need to know which items in an array are all caps, you can map over them and use the regexp test method:

const arr = ['aaa', 'aAa', 'AAa', 'AAA', 'AAAa'];
const allCaps = arr.map(el => /^[A-Z]+$/.test(el));
console.log(allCaps);

If you just need to find the first one, or filter to only include the ones that match, you can use the find or filter array methods:

const arr = ['aaa', 'aAa', 'AAa', 'AAA', 'AAAa', 'BBBB'];
const first = arr.find(el => /^[A-Z]+$/.test(el));
console.log(first);

const all = arr.filter(el => /^[A-Z]+$/.test(el));
console.log(all);


推荐阅读