简体   繁体   中英

How to convert ANSI char ID to Unicode char ID by javascript?

Function fromCharCode doesn't work with international ANSI chars. For example, for Russian ANSI (cp-1251) chars with ID from 192 to 223 it returns special characters. How to fix this issue?

I think, it's required to convert ANSI char ID to Unicode char ID and then use fromCharCode . But how to convert ANSI char ID to Unicode char ID (depending on the current locale/codepage)?

Thanks a lot for the help!

Considering that you know code page that your data is encoded in, just set up a mapping Object with keys being codes in your code page and values being proper Unicode symbols or numeric codepoints and use it to convert your data.

mapFromCP1251 = {
   192: 'А',
   193: 'Б',
   194: 'В',
   197: 'Е',
   200: 'И',
   204: 'М',
   207: 'П',
   208: 'Р',
   210: 'Т'
   // etc, I don't feel like typing entire http://en.wikipedia.org/wiki/CP1251 here
}

var string = mapFromCP1251[192] + mapFromCP1251[192] + mapFromCP1251[192] + mapFromCP1251[193] + mapFromCP1251[193] + mapFromCP1251[194]
alert(string) // АААББВ
alert(mapFromCP1251[207]+mapFromCP1251[208]+mapFromCP1251[200]+mapFromCP1251[194]+mapFromCP1251[197]+mapFromCP1251[210]+", "+mapFromCP1251[204]+mapFromCP1251[200]+mapFromCP1251[208]+"!") // Hello, world!

This is the only library I've found that solve this problem: https://github.com/Niggler/js-codepage

But it takes 1.5 MiB. Probably, if you only need a few charsets, it would take much less.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM