JS 统计字符串中大小写字母个数
注:字母a-z的code为97 - 122,A-Z的code为65 - 90 这很重要。不过记不住也没关系
let str = 'naAZiHesnKuanzgA'
console.log('a'.charCodeAt(), 'z'.charCodeAt(), 'A'.charCodeAt(), 'Z'.charCodeAt())
//97 122 65 90
function countABC(str) {
let ABC = [];
let abc = [];
for (let i in str) {
let code = str[i].charCodeAt()
if (code > 96 && code < 123) {
abc.push(str[i])
} else if (code > 64 && code < 91) {
ABC.push(str[i])
}
}
console.log(abc.length, ABC.length)
}
countABC(str)
function countABC(str) {
let strArr = Array.from(str)
let ABC = [];
let abc = [];
strArr.forEach(item => {
let code = item.charCodeAt()
if (code >= 'a'.charCodeAt() && code <= 'z'.charCodeAt()) {
abc.push(item)
} else if (code >= 'A'.charCodeAt() && code <= 'Z'.charCodeAt()) {
ABC.push(item)
}
})
console.log(abc.length, ABC.length)
}
countABC(str)
两种方法,总之怎么开心怎么来
本文介绍了一种使用JavaScript统计字符串中大写和小写字母数量的方法。通过字符编码判断,分别收集并计算字符串中大写和小写字母的数量,展示了两种不同的实现方式。

1638

被折叠的 条评论
为什么被折叠?



