zenToHan

Converts full-width Japanese alphanumeric characters to half-width ones.

by djwelsh

HTML

<label>Zen: <input type="text" id="zen" value="Forgot 2 Carry the 1..." /><input type="button" id="zentohan" value="Zen to Han!" /></label>

CSS

label {
    display: block;
    margin: 4px;
    padding: 6px;
    border: 1px solid #ccc;
}
input[type="text"] {
    width: 300px;
}

JavaScript

/*!
* jQuery zenToHan plugin
* 
* Original author: David John Welsh
* 
* This was inspired by a function written by a Japanese developer 
* here: [ http://d.hatena.ne.jp/kokoromo/20090113/1231828845 ]
* 
*  All I did was add a few extra characters and jQuerify it.
* 
* When called on a text input element, it converts any full-width 
* characters to half-width ones. This is useful if you require
* alphanumeric values that are to be entered into a database. Only 
* works on A-Z, spaces, numbers and a couple of special characters.
*/
 
;(function ($, window, document, undefined) {
 
  jQuery.fn.zenToHan = function () {
 
    return this.each(function () {
 
      var thisval = $(this).val();
 
      if (typeof(thisval) != "string") return true;
 
      var han = ' *1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@-----.,:';
      var zen = ' *1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@−ーー−—.,:';
 
      var word = thisval;
 
      for(i = 0; i < zen.length; i++) {
          var regex = new RegExp(zen[i],"gm");
          word = word.replace(regex, han[i]);
      }
      $(this).val(word);
     
    });
 
  };
})(jQuery);

//Code for the example
$('#zentohan').click(function (event) {
    $('#zen').zenToHan();
});