Convert iso-2022-jp character string to utf-8

When I received the email, it was sent by iso-2022-jp, so the characters were garbled.

Convert to utf-8 using ruby ​​encode

Generate a string encoded in iso-2022-jp for verification

puts "Hoge".encode('iso-2022-jp')
# => $B$[$2(B

Write encode as follows

str.encode(Conversion destination,Conversion source,Conversion options)

This time I want to convert the character string of iso-2022-jp to utf-8, so it will be as follows

str = "Hoge".encode('iso-2022-jp')
puts str
# => $B$[$2(B
puts str.encode('utf-8', 'iso-2022-jp', invalid: :replace, undef: :replace, replace: '')

This time I specify an option to replace the unconvertible character with an empty string

You can only convert this way if you know the source, It seems that it can be used effectively when the mail is garbled like this time.

reference

https://docs.ruby-lang.org/ja/latest/method/String/i/encode.html

Recommended Posts

Convert iso-2022-jp character string to utf-8
[Android] How to convert a character string to resourceId
Convert String type to Timestamp type
Convert to Ruby Leet string
I want to convert InputStream to String
[Convenient to remember !!!] How to convert from LocalDate type to character string and from character string to LocalDate type
[Swift] Copy the character string to the clipboard
[Java] Convert Object type null to String type
Convert to a tag to URL string in Rails
Convert from C String pointer to Swift String type
Convert a string to a character-by-character array with swift
<java> Read Zip file and convert directly to string
Sample code to convert List to List <String> in Java Stream
URL to String conversion
[Java] Convert character strings to uppercase / lowercase (AOJ⑨-swap uppercase and lowercase)
[Java] How to cut out a character string character by character
[Java] How to erase a specific character from a character string
[Kotlin] Convert ZonedDateTime to String by specifying the format
Convert a Java byte array to a string in hexadecimal notation
[Java] How to use substring to cut out a character string
I tried to convert a string to a LocalDate type in Java
Change only one character from the String type string to uppercase
[Introduction to Java] Handling of character strings (String class, StringBuilder class)
[Java] UTF-8 (with BOM) is converted to 0xFFFD (REPLACEMENT CHARACTER)
How to delete BOM (UTF-8)
About the method to convert a character string to an integer / decimal number (cast data) in Java
Convert Serializable Object to byte []
How to use String [] args
Kinx Tips --UTF8 string formatting
Convert from ○ months to ○ years ○ months
How to convert Java radix
[Java] Convert ArrayList to array
When the character string passed to C ++ by JNA is garbled
[Rails] How to omit the display of the character string of the link_to method
[Java] How to convert from String to Path type and get the path