Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *