Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

‘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', '?'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading