如何检查字符是否在字符范围内?



我想遍历一个字符串并检查特定索引处的字符是否在字母范围内;"a"通过"m">

是否有一种快速的方法来做到这一点,而不是声明一个新的字符串或对象,写出我想要的范围内的所有字母,并检查当前字母是否在该字符串或对象中的字符?

/* str takes in a string of characters such as 'askjbfdskjhsdkfjhskdjhf'
count each time a character exists thats not a letter between a-m in the alphabet */
function countOutOfRange(str) {
// count each time a letter shows up thats not within a range of letters
}

使用match和regex返回返回数组的长度,其中字母不在您的范围内。

function counter(str) {
return str.match(/[^a-m]/g).length;
}
console.log(counter('zhuresma'));
console.log(counter('bob'));
console.log(counter('abcdefghijklmnopqrstuvwxyz'));

如果你想让它更灵活:

function counter(str, range) {
const query = `[^${range[0]}-${range[1]}]`;
const regex = new RegExp(query, 'g');
return str.match(regex).length;
}
console.log(counter('zhuresma', ['a', 'b']));
console.log(counter('bob', ['a', 'm']));
console.log(counter('abcdefghijklmnopqrstuvwxyz', ['y', 'z']));

您希望使用charCodeAt()循环遍历给定字符串中的每个字符。

/* str takes in a string of characters such as 'askjbfdskjhsdkfjhskdjhf'
count each time a character exists thats not a letter between a-m in the alphabet */
function countOutOfRange(sentence, beginChar, endChar) {
// count each time a letter shows up thats not within a range of letters

let sum  = 0;

for (let i = 0; i < sentence.length; i++) {
if (sentence.charCodeAt(i) > beginChar.charCodeAt(0) && 
sentence.charCodeAt(i) < endChar.charCodeAt(0))
sum++;
}

return sum;
}
console.log(countOutOfRange('askjbfdskjhsdkfjhskdjhf', 'a', 'm'));

相关内容

最新更新