javascriptregexcase-sensitiveletterunicode-escapes

How to detect letters and theirs upper/lower case format from two characters which need to be compared to each other?


I need to get:

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', '?'));