« Back to Home

Blog

Javascriptで0パディング

2010-08-22 16:57:50 +0900

Javascriptで0パディングしたいことがあって、つい「Javascript format」で調べたのですが全然出てきませんでした。

それも当然。formatなどという関数自体が存在しないんですね。

とはいえ手動でやるなんて、とてもイヤな感じです。

var param = "1";
while (param.length < 5) {
	param = "0" + param;
}
console.debug(param);

「うーん、このループがすごく嫌。数を数えたりするのは嫌なんですよ」と思っていたところ、”Javascript 0パディング”で検索したら、こんなページが出てきました。

JavaScript でゼロパディングするときは slice を使う

この記事を参考に書くと以下のようになります。

var param = "1";
param = ("00000" + param).slice(-5);
console.debug(param);

先に足しておいて、あとで削るというわけ。これは素晴らしいですね!

元の人はMSの仕様を参照してたので、標準はどうなんだろう、というところでECMA-262を見てみることにしました。

15.5.4.13 String.prototype.slice (start, end)

The slice method takes two arguments, start and end, and returns a substring of the result of converting this object to a String, starting from character position start and running to, but not including, character position end (or through the end of the String if end is undefined). If start is negative, it is treated as sourceLength+startwhere sourceLength is the length of the String. If end is negative, it is treated assourceLength+end where sourceLength is the length of the String. The result is a String value, not a String object. (© Ecma International 2009)

sliceメソッドは2つの引数startとendを取り、このオブジェクトを文字列に変換した結果の文字列(対象文字列)の部分文字列を返す。部分文字列はstartの文字位置から始まり、endの文字位置(end自身は含まない)まで、あるいはendが与えられなかった場合は末尾までである。startが負数の場合、対象文字列長+startとして扱う。endが負数の場合、対象文字列長+endとして扱う。戻り値はStringオブジェクトではなく文字列値である。

対象文字列長+引数というのがわかりにくいですが、要は「文字位置を後ろから数える」ということです。

おや? でもこれって普通に考えたらsubstringを使いたくなる機能なのではないでしょうか? では一方その頃substringはどう定義されてるのかというと・・・

15.5.4.15 String.prototype.substring (start, end)

The substring method takes two arguments, start and end, and returns a substring of the result of converting this object to a String, starting from character positionstart and running to, but not including, character position end of the String (or through the end of the String is end is undefined). The result is a String value, not a String object.

If either argument is NaN or negative, it is replaced with zero; if either argument is larger than the length of the String, it is replaced with the length of the String.

If start is larger than end, they are swapped. (© Ecma International 2009)

substringメソッドは2つの引数startとendを取り、このオブジェクトを文字列に変換した結果の文字列(対象文字列)の部分文字列を返す。部分文字列はstartの文字位置から始まり、endの文字位置(end自身は含まない)まで、あるいはendが与えられなかった場合は末尾までである。戻り値はStringオブジェクトではなく文字列値である。

引数はいずれも、非数あるいは負数の場合は0に、対象文字列長より大きい場合は対象文字列長に置き換えられる。

startがendより大きい場合、両者は交換される。

出だしと結びはほとんど同じですね(笑)。

普通の使い方をしてるときはどちらも同じ機能を果たしますが、負数になったり文字列長を超えたりすると挙動が違ってくるので要注意、といったところでしょうか。

なんとなーく(偏見で)、sliceからはNetscape系、substringからはMS系のニオイがします。substringは置き換えちゃったり交換しちゃったりして勝手な印象・・・。