Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert full-width Japanese text to half-width (zen-kaku to han-kaku)

In PHP it's possible to convert double-width characters to single width with the function mb_convert_kana. They call it "convert zen-kaku to han-kaku". For example, I have a string to convert:

dbl = "BOX"

and I'd like to find some method like this

dbl = "BOX".convert_to_half_width # dbl is now "BOX"

Is there a way to do this in Ruby?

like image 349
nevan king Avatar asked Jun 20 '12 10:06

nevan king


1 Answers

I use a combination of the Ruby built-in NKF and String#tr

require 'nkf'
dbl = "BOXカタカナ"
dbl = NKF.nkf('-X -w', dbl).tr('0-9a-zA-Z', '0-9a-zA-Z')
# dbl now is "BOXカタカナ"

This has the added benefit of transposing half-width katakana to full-with katakana as well.

like image 108
sleepy_keita Avatar answered Sep 19 '22 04:09

sleepy_keita