Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell whether KeyboardEvent.key is a printable character or control character?

Tags:

javascript

I'm writing a keypress event which executes special functions for certain control characters, but inserts any printable character into a string.

this.handle_keypress = function(event) {
    let callback = this.control_function[event.key];
    if(callback) {
        callback.bind(this)(event);
    }
    else {
        this.myText += event.key;
    }
}

this.element.addEventListener('keypress', this.handle_keypress.bind(this));

But this will insert the text for unmapped control characters into my string (e.g. 'LeftArrow' or 'Backspace'). How can I tell which characters are printable characters and which are control characters?

Back in the day, I would use event.which or event.charCode, but these are marked as deprecated now.

I cannot use the input event, as far as I know, because I am not typing into a textarea or input field.

I'm running this in Firefox.

like image 834
eiko Avatar asked Nov 07 '22 04:11

eiko


1 Answers

There's no immediately way to determine if event.key is a control character. But given that:

  • the names of control characters are all currently multiple chars long (e.g., "Escape") and only contain letters and numbers
  • the length of ASCII characters is 1
  • non-ASCII characters contain bytes outside the range of [a-zA-Z]

You can make a code to decide between either or:

var letters = [];

elm.addEventListener("keydown", function(e) {
  if(e.key.length == 1 || (e.key.length > 1 && /[^a-zA-Z0-9]/.test(e.key))) {
    letters.push(e.key);

  } else if(e.key == "Spacebar") {
    letters.push(" ");
  }
}, false);
like image 105
Kernel James Avatar answered Nov 15 '22 07:11

Kernel James