js-challenges
js-challenges copied to clipboard
字符串中字母的出现次数
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
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
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);
function countCharacters(str) {
let charCount = {};
for(let i = 0; i < str.length; i++) {
let char = str[i];
if(char.match(/[a-zA-Z]/i)) { // 只考虑字母
if(charCount[char]) {
charCount[char]++;
} else {
charCount[char] = 1;
}
}
}
return charCount;
}
function strNumber(str) {
let reg = /[a-zA-Z]/;
let map = new Map();
for (let i = 0; i < str.length; i++) {
if (reg.test(str[i])) {
if (map.has(str[i])) {
let num = map.get(str[i]);
map.set(str[i], num + 1);
} else {
map.set(str[i], 1);
}
}
}
console.log(map);
}
strNumber("abcdeabdasjklhsafhgkjsdnioqwjldask123276543");
const a = 'abcdeabdasjklhsafhgkjsdnioqwjldask123276543';
function getCount(a) {
let count = 0;
let reg = /[a-zA-Z]/;
console.log(a.length);
for(var i = 0; i < a.length; i++) {
if(reg.test(a[i])) {
count++;
}
}
return count;
}
console.log(getCount(a));