金額桁区切り

金額とかを3桁区切りでカンマを入れたい時用です。

金額入力:
金額出力:

Script解説
正規表現で、文字列の後ろから3文字づづとっていって、カンマを入れているだけです。
もっとスマートな方法はあるとは思いますが...

というわけでもう少しスッキリした方法を作成しました。ポイントは文字列の逆転です。
正規表現のマッチパターンが配列になることを利用して、
reverse()で逆転、配列要素をjoin("")で再結合すると元の文字列をひっくり返した文字列がえれます。
後は頭から3桁ずつ「,」を入れて再び元に戻します。
このとき先頭に「,」が来る場合に備えreplace(/^,/,"")を入れています。
文字列をひっくり返す処理はいろいろ使えそうかな。
以下Script
  function format(str){
    temp1 = '';
    temp2 = str.match(/...$/);
    while(temp2 != null){
      temp1 = temp2 + ','+temp1;
      str = str.replace(/...$/,'');
      temp2 = str.match(/...$/);
    }
    temp1 = (str!='') ? str + ',' + temp1 : temp1;
    temp1 = temp1.replace(/.$/,"");
    return temp1;
  }
  
  //正規表現を駆使した方法
  function format2(str){
    var temp1 = str.match(/./g).reverse().join("");
    temp1 = temp1.replace(/(\d{3})/g,"$1,");
    temp1 = temp1.match(/./g).reverse().join("").replace(/^,/,"");
    return temp1;
  }

  

金額桁区切り
WebSite :JavaScriptの部屋別館
E-Mail   :blaze@gol.com
最終更新日 :2001/01/24