Posted By

szsk on 08/03/06


Tagged

javascript String japanese


Versions (?)

string_z2h


 / Published in: JavaScript
 

URL: http://snipplr.com/users/szsk/

全角文字を半角文字に

  1. Array.prototype.clone = function( ) {
  2. return Array.apply( null, this );
  3. }
  4. String.prototype.z2h = function( ignorechars ) {
  5. //無視文字列が渡されているなら配列を複製
  6. var tb = ( ignorechars ) ? z2h_tb.clone( ) : z2h_tb;
  7.  
  8. //無視する文字を消していく
  9. for( var i = 0, len = ignorechars.length; i < len; i++ )
  10. tb[ ignorechars.charCodeAt( i ) ] = "";
  11.  
  12. return this.replace(
  13. /[\u3000-\u3002\u300C\u300D\u309B\u309C\u30FB\u30FC\u30A1-\u30F4\uFF01-\uFF5E\uFFE5]/g
  14. , function( $0 ) { return tb[ $0.charCodeAt( 0 ) ] || $0; } );
  15. }
  16.  
  17. var zk = '。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゛゜';
  18. var hk = '。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙゚';
  19.  
  20. //全角文字を半角文字に変換
  21. var z2h_tb = [];
  22.  
  23. //英数記号
  24. for( i = "!".charCodeAt( 0 ), len = "~".charCodeAt( 0 ); i <= len; i++ )
  25. z2h_tb[i] = String.fromCharCode( i - 0xFEE0 );
  26. z2h_tb[" ".charCodeAt( 0 )] = " ";
  27. z2h_tb["¥".charCodeAt( 0 )] = "\\";
  28.  
  29. //カナ
  30. for( i = 0, len = zk.length; i <= len; i++ )
  31. z2h_tb[ zk.charAt( i ).charCodeAt( 0 ) ] = hk.charAt( i );
  32.  
  33. //濁点・半濁点付き
  34. z2h_tb["ガ".charCodeAt( 0 )] = "ガ";
  35. z2h_tb["ギ".charCodeAt( 0 )] = "ギ";
  36. z2h_tb["グ".charCodeAt( 0 )] = "グ";
  37. z2h_tb["ゲ".charCodeAt( 0 )] = "ゲ";
  38. z2h_tb["ゴ".charCodeAt( 0 )] = "ゴ";
  39. z2h_tb["ザ".charCodeAt( 0 )] = "ザ";
  40. z2h_tb["ジ".charCodeAt( 0 )] = "ジ";
  41. z2h_tb["ズ".charCodeAt( 0 )] = "ズ";
  42. z2h_tb["ゼ".charCodeAt( 0 )] = "ゼ";
  43. z2h_tb["ゾ".charCodeAt( 0 )] = "ゾ";
  44. z2h_tb["ダ".charCodeAt( 0 )] = "ダ";
  45. z2h_tb["ヂ".charCodeAt( 0 )] = "ヂ";
  46. z2h_tb["ヅ".charCodeAt( 0 )] = "ヅ";
  47. z2h_tb["デ".charCodeAt( 0 )] = "デ";
  48. z2h_tb["ド".charCodeAt( 0 )] = "ド";
  49. z2h_tb["バ".charCodeAt( 0 )] = "バ";
  50. z2h_tb["ビ".charCodeAt( 0 )] = "ビ";
  51. z2h_tb["ブ".charCodeAt( 0 )] = "ブ";
  52. z2h_tb["ベ".charCodeAt( 0 )] = "ベ";
  53. z2h_tb["ボ".charCodeAt( 0 )] = "ボ";
  54. z2h_tb["パ".charCodeAt( 0 )] = "パ";
  55. z2h_tb["ピ".charCodeAt( 0 )] = "ピ";
  56. z2h_tb["プ".charCodeAt( 0 )] = "プ";
  57. z2h_tb["ペ".charCodeAt( 0 )] = "ペ";
  58. z2h_tb["ポ".charCodeAt( 0 )] = "ポ";
  59. z2h_tb["ヴ".charCodeAt( 0 )] = "ヴ";
  60.  
  61. //--------------------------//
  62.  
  63. alert( "アイウエオガギグゲゴパピプペポ。「」、・".z2h( ) );
  64. //アイウエオガギグゲゴパピプペポ。「」、・

Report this snippet  

You need to login to post a comment.