user1432306
user1432306

Reputation: 11

charCodeAt to return correct code for custom charcodes

Would this be good way to return correct code for custom charcodes

String.prototype._charCodeAt = String.prototype.charCodeAt;
String.prototype.charCodeAt = function( i , keycodes ) {
    if( keycodes !== 'undefined' ) {
        for( var j = 0; j < keycodes.length; j++ ) {
            if( this[i] === keycodes[j].char ) {
                return keycodes[j].code;
            }
        }
    } else {
        return this._charCodeAt( i );
    }
}

Keycodes is array where values stored like this

[
    ...
    { "char" : "ä" , "code" : 132 },
    { "char" : "à" , "code" : 133 },
    { "char" : "å" , "code" : 134 },
    ...
];

By default the javascript returns wrong values for the "special characters".
Is this code sufficient for this?

Upvotes: 1

Views: 496

Answers (1)

Esailija
Esailija

Reputation: 140230

You can simply use an object:

var codes = {
    "ä": 132,
    "à": 133,
    "å": 134
};

function customCharCodeAt( string, index ) {
    return codes[string.charAt(index)] || string.charCodeAt(index);
}

You should not override the normal charCodeAt function as it does return correct and expected values.

Upvotes: 1

Related Questions