Search code examples
javascripteventscharkey

Get key char (value) from keycode with shift modifier


I have been lucky to find String.fromCharCode(). It has helped me significantly. However, I noticed it doesn't take into account the shift modifier. I know the event.shiftKey property and use it, but right now I need to get the key value (eg: "A" or "a") which takes into account the shift key modifier. At first I used String.toLowerCase().. But I neglected to think of number keys, to give one example: "5" (without shift) and "%" (with shift). I need to differentiate between the two in my program. What's an easy way to get the key char value?


Solution

  • This brute force technique isn't the prettiest, but it seems to work. I'm in search of the same functionality.

    function mapKeyPressToActualCharacter(isShiftKey, characterCode) {
        if ( characterCode === 27 || characterCode === 8 || characterCode === 9 || characterCode === 20 || characterCode === 16 || characterCode === 17 || characterCode === 91 || characterCode === 13 || characterCode === 92 || characterCode === 18 ) {
            return false;
        }
        if (typeof isShiftKey != "boolean" || typeof characterCode != "number") {
            return false;
        }
        var characterMap = [];
        characterMap[192] = "~";
        characterMap[49] = "!";
        characterMap[50] = "@";
        characterMap[51] = "#";
        characterMap[52] = "$";
        characterMap[53] = "%";
        characterMap[54] = "^";
        characterMap[55] = "&";
        characterMap[56] = "*";
        characterMap[57] = "(";
        characterMap[48] = ")";
        characterMap[109] = "_";
        characterMap[107] = "+";
        characterMap[219] = "{";
        characterMap[221] = "}";
        characterMap[220] = "|";
        characterMap[59] = ":";
        characterMap[222] = "\"";
        characterMap[188] = "<";
        characterMap[190] = ">";
        characterMap[191] = "?";
        characterMap[32] = " ";
        var character = "";
        if (isShiftKey) {
            if ( characterCode >= 65 && characterCode <= 90 ) {
                character = String.fromCharCode(characterCode);
            } else {
                character = characterMap[characterCode];
            }
        } else {
            if ( characterCode >= 65 && characterCode <= 90 ) {
                character = String.fromCharCode(characterCode).toLowerCase();
            } else {
                character = String.fromCharCode(characterCode);
            }
        }
        return character;
    }