javascriptencodingutf-8characterconverters

JavaScript function to convert UTF8 string between fullwidth and halfwidth forms


EDIT: Thanks to GOTO 0, I now know exactly what I my question is called.

I need a JavaScript function to convert from UTF-8 fullwidth form to halfwidth form.


Solution

  • Try this

    function toASCII(chars) {
        var ascii = '';
        for(var i=0, l=chars.length; i<l; i++) {
            var c = chars[i].charCodeAt(0);
    
            // make sure we only convert half-full width char
            if (c >= 0xFF00 && c <= 0xFFEF) {
               c = 0xFF & (c + 0x20);
            }
    
            ascii += String.fromCharCode(c);
        }
    
        return ascii;
    }
    
    // example
    toASCII("ABC"); // returns 'ABC' 0x41