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
  • 204,599
  • 20
  • 195
  • 236
jgrewal
  • 342
  • 1
  • 10

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
  • 30,714
  • 6
  • 20
  • 43
  • 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