Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

How can I convert a text file or a String from UTF-8 format to ASCII?

For example, the following string "ZÜRICH-ZOLLI" once outputted into a text file. If the file has the format UTF-8 is has 13 characters but when the format is ASCII the number of characters is 12.

The endpoint where the file is being sent only accepts the ASCII-encoded version, and fails on the UTF-8 encoded string salesforce normally produces.

share|improve this question

2 Answers 2

UTF-8 is a superset of ASCII. The character codes 0-127 (i.e. the ASCII characters) are directly mapped to the binary values 0-127 so if your UTF-8 string only consists of ASCII characters it is already in ASCII format.

Beyond that all you can really do is strip out the non-ascii characters from your string or replace them with some ASCII character. This regex should do it for you.

if(!str.isAsciiPrintable) str = str.replaceall('[^\\x00-\\x7F]', '');
share|improve this answer
data = EncodingUtil.urlEncode(data, 'ASCII');
data = EncodingUtil.urlDecode(data, 'ASCII');

(What if there is a byte order marker?)

share|improve this answer
2  
this worked for me! and I was able to strip the remnant byte order mark as well –  Wesley Jan 18 '13 at 12:48
    
That's interesting. I guess this would depend on whether you want to strip out the characters or replace with a '?'. Though of course you could easily modify replaceall to use a '?'. –  Greg Grinberg Jan 18 '13 at 19:11
1  
the ?s are a bummer :( off-platform, iconv //TRANSLIT could at least represent Ü as U –  user320 Jan 18 '13 at 20:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.