Home > Back-end >  How to stop regex from picking up character matches when Ctrl, Shift, etc. are pressed?
How to stop regex from picking up character matches when Ctrl, Shift, etc. are pressed?

Time:01-25

I was tasked with making a code that picks up when a key is pressed and counts the number of characters typed. I decided to use var regex=/[a-zA-Z0-9]/;, but to my surprise, when I pressed Enter, Shift, Ctrl, or Alt, it would register all of them.

Here is the snippet of code that matters:

window.onload = init;

function init() {
    window.onkeyup = incrementKey;
}

function incrementKey() {
    console.log(event.key)

    var regex=/[a-zA-Z0-9]/;

    if (event.key.match(regex)) {
        console.log(event.key)
    }
}

This way I’ll see the character show up twice if picked up by regex, and once if not. And I have already tried nearly everything on the W3Schools documentation on RegExp.

Things that I tried: [A-Za-z0-9], [^\n] (also tried with \0, \n, \f, \r, \t, \v), [\w], [] (obviously, at least, here, it doesn’t register any keys).

I was wondering how I can exclude the characters that don’t change the context of the text, other than manually typing every single character on its own.

CodePudding user response:

If you want to use a regex to filter out the a-zA-Z0-9 characters then your original almost correct what your looking for is ^[a-zA-Z0-9]$ this regex will only match one character; anything between ^ and $ in a regex means that the pattern must start at the beginning of a string and end at the end of a string. Your original answer failed because [a-zA-Z0-9] searches the string for all one character long alphanumerical substrings, obviously the string "Enter" still has alphanumerical characters therefore your regex.match will result in a match.

Alse you could consider using regex.test(str) as it returns a boolean, you can read more about it over at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

  • Related