Javascript: convert full-width and half-width string

Convert

String.prototype.toHalfWidth = function() {
    return this.replace(/[A-Za-z0-9]/g, function(s) {return String.fromCharCode(s.charCodeAt(0) - 0xFEE0)});
};

String.prototype.toFullWidth = function() {
    return this.replace(/[A-Za-z0-9]/g, function(s) {return String.fromCharCode(s.charCodeAt(0) + 0xFEE0);});
};
Usage:
'aBc123'.toHalfWidth(); // abc123
'abc123'.toFullWidth(); // aBc123

Disable suggestions

When type japanese, system will auto suggestions to change to full-width, half-width, kanji ... But when we create an input that auto convert from full-width number to half-width number, we dont want that suggestions showing anymore. This is a solution:
<input type="text" />
$('input').keyup(function(){
    var target = $(this);
    var val = target.val();
    target.val('  '); // double space
    target.val(val.toHalfWidth());
});

Comments

Popular Posts