Home > Mobile >  How to check if a character is within a range of characters?
How to check if a character is within a range of characters?

Time:04-25

I want to iterate over a string and check whether a character at a specific index is within a range of letters; "a" through "m" in the alphabet.

Is there a quick way to do this instead of declaring a new string or object and writing out all the letters within my desired range and checking to see if the current letter is a character within that string or object?

/* 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
   }

CodePudding user response:

Use match with a regex to return the length of the returned array where letters are not within your range.

function counter(str) {
  return str.match(/[^a-m]/g).length;
}

console.log(counter('zhuresma'));
console.log(counter('bob'));
console.log(counter('abcdefghijklmnopqrstuvwxyz'));

If you want it to be more flexible:

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']));

CodePudding user response:

You want to use charCodeAt() to loop through each character in the given string.

/* 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'));

  • Related