2

I know how to get the key of a character. for example console.log(String.fromCharCode(70)) would log the letter F

but how do I do the opposite and get the CharCode from a single letter string?

What I tried:


function solution(someword) {
  let oneArray = someword.split("");
  let onekey = String.fromCharCode(oneArray[0])
  console.log(onekey)
}

solution("FROG");

if my word is FROG. it should console log 70 since F is the first letter

epascarello
  • 195,511
  • 20
  • 184
  • 225
jgrewal
  • 274
  • 1
  • 7

1 Answers1

3

Use String.charCodeAt:

function solution(someword) {
    let onekey = someword.charCodeAt(0)
    console.log(onekey) 
}

solution("FROG")
console.log(String.fromCharCode(70))
Spectric
  • 27,594
  • 6
  • 14
  • 39
  • 1
    Why not just `let onekey = someword.charCodeAt(0)`? What does `.split("")` accomplish given that `charCodeAt` already accesses a character in the string by its index? – Wyck Nov 23 '21 at 21:28
  • 1
    @Wyck Good point. I've updated my answer. Thanks! – Spectric Nov 23 '21 at 21:29