How to get character value from key code in JavaScript then trim?

Sometimes, we want to get character value from key code in JavaScript then trim.

In this article, we’ll look at how to get character value from key code in JavaScript then trim.

How to get character value from key code in JavaScript then trim?

To get character value from key code in JavaScript then trim, we can use the string fromCharCode method.

For instance, we write

document.onkeydown = (e) => {
  let keyCode = e.keyCode;
  let chrCode = keyCode - 48 * Math.floor(keyCode / 48);
  let chr = String.fromCharCode(96 <= keyCode ? chrCode : keyCode);
  console.log(chr);
};

to get the keyCode from the keydown event object e to get the key pressed.

Then we get the chrCode character code from the keyCode with keyCode - 48 * Math.floor(keyCode / 48).

Then we get the character from charCode with String.fromCharCode.

Conclusion

To get character value from key code in JavaScript then trim, we can use the string fromCharCode method.