A function that will check if two given characters

I need to get:

  • If either of the characters is not a letter, return -1
  • If both characters are the same case, return 1
  • If both characters are letters, but not the same case, return 0

Examples:

‘a’ and ‘g’ returns 1

‘A’ and ‘C’ returns 1

‘b’ and ‘G’ returns 0

‘B’ and ‘g’ returns 0

‘0’ and ‘?’ returns -1

Now my code is uncorrect:

function sameCase(a, b) {

  if (a.match(/a-z/) && b.match(/a-z/)) {
    return 1;
  }
  if (a.match(/A-Z/) && b.match(/A-Z/)) {
    return 0;
  }
  if (b.match(/a-z/) && a.match(/A-Z/)) {
    return 0;
  }

  return -1;
}

console.log(sameCase('a', 'b'));
console.log(sameCase('A', 'B'));
console.log(sameCase('a', 'B'));
console.log(sameCase('B', 'g'));
console.log(sameCase('0', '?'));

Help, please..

>Solution :

You are using regex incorrectly. You should have used /[a-z]/ if you want to check that your character is a letter from a to z.

function sameCase(a, b){
  if (a.match(/[a-z]/) && b.match(/[a-z]/)) {
    return 1;
  }
  if (a.match(/[A-Z]/) && b.match(/[A-Z]/)) {
    return 1;
  }
  if (b.match(/[a-z]/) && a.match(/[A-Z]/)) {
    return 0;
  }
  if (a.match(/[a-z]/) && b.match(/[A-Z]/)) {
    return 0;
  }
  return -1;
}
console.log(sameCase('a', 'b'));
console.log(sameCase('A', 'B'));
console.log(sameCase('a', 'B'));
console.log(sameCase('B', 'g'));
console.log(sameCase('0', '?'));

Leave a Reply