15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでゼロパディングとゼロサプレス

Last updated at Posted at 2019-02-07

ゼロパディングとゼロサプレス

ゼロパディング・ゼロサプレスとは、

ゼロパディング 【 zero padding 】 ゼロ埋め / ゼロサプライ / 前ゼロ

ゼロパディングとは、数値を文字として表現・表示する際に、指定された桁数に足りない分だけ左右に「0」を追加する処理のこと。決まった長さ(固定長)の文字列に変換したいときに行われる。

ゼロサプレス (zero suppress)
これとは逆に、「0012.3400」を「12.34」にするといったように、先頭あるいは末尾の余分な「0」を削除したり空白で置き換え、数値としての本来の表記に戻す処理のことは「ゼロサプレス」(zero suppress)という。ゼロパディングと意味を取り違えやすいので注意が必要である。

JavaScriptでゼロパディング

String.prototype.padStart()を使います。

String.prototype.padStart()

str.padStart(targetLength [, padString])
パラメーター
targetLength
現在の文字列の延長後の長さ。パラメーターが現在の文字列の長さよりも短い場合、現在の文字列が返される。
padString Optional
現在の文字列を延長するための文字列。この文字列が長すぎる場合、切り捨てられて、左の部分が適用されます。 このパラメーターの既定値は、" " (U+0020) です。
戻り値
現在の文字列の先頭に延長が適用された String

// 例:'1234567'をゼロパディング
const padded = '1234567'.padStart(8, '0')
console.log(padded) // '01234567'

JavaScriptでゼロサプレス

様々な方法があると思いますが、今回は簡単なのでLodashのtrimStartを使います。

Lodash trimStart

_.trimStart([string=''], [chars=whitespace])

Removes leading whitespace or specified characters from string.

Arguments
[string=''](string): The string to trim.
[chars=whitespace](string): The characters to trim.

Returns
(string): Returns the trimmed string.

// 例:'01234567'をLodashのtrimStartでゼロサプレス
const trimmedString = trimStart('01234567', '0');
console.log(trimmedString); // '1234567' 

LodashのpadStartを使ったゼロパディング

ちなみにLodashのpadStartを使ってもゼロパディングができます。

Lodash padStart

_.padStart([string=''], [length=0], [chars=' '])
Pads string on the left side if it's shorter than length. Padding characters are truncated if they exceed length.

Arguments
[string=''](string): The string to pad.
[length=0](number): The padding length.
[chars=' '](string): The string used as padding.

Returns
(string): Returns the padded string.

// 例:'1234567'をLodashのpadStartでゼロパディング
const paddedString = padStart('1234567', 8, '0');
console.log(paddedString); // '01234567'
15
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?