「JavaScript」sliceメソッドで頭ゼロをつけるサンプル

書式
arr.slice([start[, end]])
start
取り出しの開始位置を示す 0 から始まるインデックスです。
end
取り出しを終える直前の位置を示す 0 から始まるインデックスです。slice は end 自体は含めず、その直前まで取り出します。
戻り値
取り出された要素を含む新しい配列です。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const str = "8";
console.log(("000" + str).slice(-3));
console.log(("00000" + str).slice(-5));
const stg = "70";
console.log(("000" + stg).slice(-3));
console.log(("00000" +stg).slice(-5));
const str = "8"; console.log(("000" + str).slice(-3)); console.log(("00000" + str).slice(-5)); const stg = "70"; console.log(("000" + stg).slice(-3)); console.log(("00000" +stg).slice(-5));
const str = "8";
console.log(("000" + str).slice(-3)); 
console.log(("00000" + str).slice(-5)); 

const stg = "70";
console.log(("000" + stg).slice(-3)); 
console.log(("00000" +stg).slice(-5));

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"008"
"00008"
"070"
"00070"
"008" "00008" "070" "00070"
"008"
"00008"
 "070"
 "00070"

 

JavaScript

Posted by arkgame