Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

字符串中字母的出现次数

Sunny-117 opened this issue · comments

字符串中字母的出现次数
const str = "ABCabc123"
let res = 0
for (const c of str)
    if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
        res++
console.log(res)  // 6
commented
function count(str){
    let res = 0;
    for(let i = 0; i < str.length; i++){
        if(str[i] >= 'a' && str[i] <= 'z' || (str[i] >= 'A' && str[i] <= 'Z')) res++;
    }
    return res;
}
console.log(count("ABCabc123"));

如果是要统计每个字母的次数,可以用map

commented
const reg = /[^a-zA-Z]/g;
const str = "ABCabc123";
console.log(str.replaceAll(reg, '').length)
const str = "ABCabc123";
let res = str.split("").reduce((pre, cur) => {
  if (!pre[cur]) pre[cur] = 1;
  else pre[cur]++;
  return pre;
}, {});
console.log(res);