Javascript String.fromCharCode Case Sensitivity?

你离开我真会死。 提交于 2019-11-30 21:45:14

问题


I am simply listening for a keyup event of an input element and gather the results into a string like so

word=word+String.fromCharCode(key.keyCode);

The problem is that the word is in capital letters while I want it to be case-sensitive. For example if I type abcef my accumulated word becomes 'ABCEF' .

Note - I need a pure javascript solution (no libraries..) Any thoughts?


回答1:


Events like keyup and keydown will return 65 for both a and A (and also true for event.shiftKey if that key is held down).

The keypress event returns different keycodes for upper and lower case letters, so to get this working case sensitive you should use the keypress event, and fromCharCode() will return the correct letter, case sensitive.




回答2:


You can always call .toLowerCase()

word = word + String.fromCharCode(key.keyCode).toLowerCase();

Might make more sense to call .toLowerCase() just once, at the point you decide you're finished accumulating characters.



来源:https://stackoverflow.com/questions/14943966/javascript-string-fromcharcode-case-sensitivity

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