0
0

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 3 years have passed since last update.

JavaScriptで数字の桁数を0で揃える方法

Last updated at Posted at 2019-05-14

JavaScriptで数字の桁数を0で揃える方法

英語でいう"zero padding"です。(英語でなんて言うかを知っておくのは大事なのでぜひ覚えてみて下さい。)

さて、JavaScriptのzero paddingには
String​.prototype​.pad​Start()
が使えます。zero paddingに関わらず、任意の文字で先頭を埋めることが出来ます。

以下、公式のコードです。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

const str1 = '5';

console.log(str1.padStart(2, '0'));
// expected output: "05"

const fullNumber = '2034399002125581';
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, '*');

console.log(maskedNumber);
// expected output: "************5581"

ぜひ使ってみてください。

終わりに

私は現在、Web3のサービスの開発をしています。詳しくはこちらの記事をご覧下さい。
無料でイーサリアムが当たる、Web3時代の寄付サイトを作った話

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?