-4

I have to create a program that takes the first letter of a prompt, and if that letter is between a and k, then it has to produce a certain output, if it's between l and p another and so on. Is there a way to do this without writing every letter of the alphabet down? (sorry I'm a new coder)

  • 2
    what have you tried ? you could use the basic comparison(relational) operators – Dhananjai Pai Sep 30 '19 at 15:39
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt – benvc Sep 30 '19 at 15:40
  • 1
    Take a look at [`charCodeAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt) and [`fromCharCode`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode). – Andy Sep 30 '19 at 15:40

1 Answers1

0

I think you should try to solve the problem, before asking - so you can show what you've already tried.

I think the snippet below points you in the right direction - but it takes any character, not just letters. You need to get everything filtered out that's not a lower case letter.

// UI elements
const input = document.getElementById('input1')
const result = document.getElementById('result')

// input event
// only the first character is taken into account
input.addEventListener('input', function(e) {
  // adding the characters of the input value to an array, and
  // picking the 0th element (or '', if there's no 0th element)
  const a = [...this.value][0] || ''
  let ret = ''

  if (a !== '') {
    // lowercaseing letters, so it's easier to categorize them
    ret = categorizeAlphabet(a.toLowerCase().charCodeAt(0))
  } else {
    ret = 'The input is empty'
  }

  // displaying the result
  result.textContent = ret
})

// you could use this function to filter and categorize
// according to the problem ahead of you - and return the result
// to be displayed.
// In this example this function is rather simple, but
// you can build a more complex return value.
const categorizeAlphabet = (chCode) => {
  return `This is the character code: ${chCode}`
}
<label>
  First character counts:
  <input type="text" id='input1'>
  </label>
<h3 id="result">The input is empty</h3>
muka.gergely
  • 8,063
  • 2
  • 17
  • 34