Search code examples
javascriptspecial-charactersuppercaselowercase

Javascript check if first character is number, upperCase, lowerCase or special character


The goal is a program that checks if the first character they type is a number, uppercase letter, lowercase letter or a special character/other.

Number works absolutely fine, but my task has to compare the uppercase and lowercase and check if they are letters. If not, it should then return special character. I also have to make it without using functions.

I am struggling to get the special character to display as it is treated as either uppercase or lowercase. I have tried fiddling around with the equals signs and using regex but I am confusing myself. onlyLetters as you can see it not being used as I have tried making it == to input. Doing this led to everything (except numbers) being shown as a special character and thus reversing the problem. I have also tried seeing what works for others but they do not work on uppercase and lowercase letters also like I am.

Is there way to return an uppercase letter, lowercase letter or special character without the use of a function? Help to restore sanity is greatly appreciated

let input = prompt('Enter a number or uppercase or lowercase letter')
let onlyLetters = /^[a-zA-Z]/
const upperCase = input.toUpperCase()
const lowerCase = input.toLowerCase()
const numInput = Number(input)

if (Number.isInteger(numInput) == true) {
  console.log(input + ' is a number')
} else if (input === upperCase || lowerCase) {
  if (input === upperCase) {
    console.log(input + ' is an uppercase letter')
  } else if (input === lowerCase) {
    console.log(input + ' is a lowercase letter')
  }
} else {
  console.log(input + ' is a special character')
}


Solution

  • you have an error here

    if (input === upperCase || lowerCase) {

    should be

    if (input === upperCase || input === lowerCase) {

    But just use the regex you had but did not use

    let input = prompt('Enter a number or uppercase or lowercase letter')
    const numInput = Number(input)
    
    if (Number.isInteger(numInput)) {
      console.log(input + ' is a number')
    } else if (input.match(/[a-zA-Z]/)) {
      const upperCase = input.toUpperCase()
      const lowerCase = input.toLowerCase()
      if (input === upperCase) {
        console.log(input + ' is an uppercase letter')
      } else if (input === lowerCase) {
        console.log(input + ' is a lowercase letter')
      }
    } else {
      console.log(input + ' is a special character')
    }