javascript - 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');
}
})
}
}
解决方案
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);
推荐阅读
- c# - Azure DevOps - PowerApps package Deployer - You cannot call a method on a null-valued expression
- python - 如何使用 urllib 获取网页的 html?
- asp.net-core - Loading content into Blazor TabControl
- c# - 是什么导致 Unity 3D 中的“WrongThreadException”?
- c# - Proper way to create a singleton service in ASP.NET Core - does it have to use the static keyword, or not?
- c# - 序列化和向后兼容性 (DataContractJsonSerializer)
- vue.js - Laravel 中多个 Vue 实例/应用程序的最佳实践
- json - powershell psobject nested with same reference. from json
- c++ - 使用 QBarCategoryAxis 限制 QChart 上的滚动
- javascript - 记录通过函数生成的类(混合)