String.fromCharCode issue for special characters in javascript

Deadly 提交于 2021-02-05 11:50:24

问题


Below code accepts a character and prints character using keycode(String.fromCharCode). Issue arises when you enter special character like . or ?.

function logChar(e){
  var keyCode = e.which || e.keyCode;
  var char = String.fromCharCode(keyCode);
  console.log(char)  
}
<input type="text" onkeydown="logChar(event)" />

Can someone explain why is it returning different value and how to get same value?

Thanks in advance!


回答1:


That's because keyCode and charCode are different. String.fromCharCode assumes that the input is unicode (so A is 65), and for the letter and number keys, they will match... sort of. You will notice that 'a' and 'A' as a keyCode both come out as 65, but 'a' is 97! So keyCode is just an identifier for the actual key on the keyboard that you press and is not unicode.

That's why the numpad 0-9 gives different codes too. If you want to map the key presses, use a site like this. But note you will never get the exact character out again.



来源:https://stackoverflow.com/questions/34768354/string-fromcharcode-issue-for-special-characters-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!