紀錄工作經驗、相關知識,解決技術相關問題。

Javascript, 新手 Jamp Holes, 網站相關, 資訊相關

Leading zero 前導零 – JS 數字前補 0 (padStart 用法)

Leading zero 前導零 - JS 數字前補 0 (padStart 用法) 特色圖片

Leading zero(前導零),也就是常在編號或月份日期前方看到的一串補 0(詳細定義可參閱維基百科:Leading zero)。在前端開發中,實作 JS 數字前補 0 最常應用於訂單流水號對齊(如 000123)與時間顯示(如 09:05);若您的需求相反,是要在數字或小數點後方補零,則可參考 JavaScript 數字後面補 0(Trailing Zero)。


一、 核心複製即用範本與前導零處理對照

直觀的數字前補 0(以目標總長度 9 位數為例)對比如下:

一般數字經過 Leading Zero 前補 0 處理(9 位數)常見應用場景
123000000123會員編號、商品序號對齊
44444000044444固定長度金融電文欄位
5566666005566666資料庫流水號顯示
7890000007890發票或憑證號碼格式統整
9876543009876543條碼與憑證字軌補齊

二、 3 種 JS 數字前面補 0 實作方法

1. 使用 ES2017 String.prototype.padStart()(現代標準寫法)

在現代瀏覽器與 Node.js 環境中,最簡潔的做法是先用 String() 將數字轉為字串,再呼叫 padStart(目標長度, '0')。當字串長度不足目標長度時,會自動在左側開頭補滿 '0':

/**
 * 將數字或字串左側前補 0 至指定長度
 * @param {number|string} code - 原始輸入資料
 * @param {number} targetLength - 補 0 後的目標總長度
 * @returns {string} 補零後的字串
 */
function padLeadingZero(code, targetLength) {
  return String(code).padStart(targetLength, '0');
}

console.log(padLeadingZero(123, 9));       // 輸出: "000000123"
console.log(padLeadingZero('abc123', 10)); // 輸出: "0000abc123"

// 常見實務場景:日期月份與時分秒補 0(固定 2 位數)
const month = 5;
const day = 9;
console.log(`${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
// 輸出: "05-09"

2. 使用 Array.join('0') 與 slice()(支援超過長度截斷)

若除了在前方補 0 之外,還希望當輸入長度超過 dataLength 時只保留末尾指定位數,可使用 Array.join('0') 搭配負數索引 slice(-dataLength):

// 數字、字串前補 0
// code : 輸入的資料(字串或數字)
// dataLength : 資料補 0 後的長度
function LeadingZero(code, dataLength) {
  var str = Array(dataLength + 1).join('0') + code;
  return str.slice(0 - dataLength);
}

var str = 'abc123';
console.log(LeadingZero(str, 10));
// 輸出: "0000abc123"

如果希望前面補的不是數字 '0',而是其他自訂代號(例如 '*' 或 '#'),直接把 join('0') 或 padStart(targetLength, '0') 中的 '0' 改成要補的字元即可。

3. 相容早期 IE 老系統寫法

若維護的系統仍需在早期 IE 環境執行,可預先串接固定長度的 '0' 字串,再透過 slice(0 - dataLength) 由右往左截取指定長度:

// input: (123, 8) , output : "00000123"
function LeadingZeroLegacy(code, dataLength) {
  var str = '0000000000' + code;
  return str.slice(0 - dataLength);
}

var str = 'abc123';
console.log(LeadingZeroLegacy(str, 10));
// 輸出: "0000abc123"

三、 常見問題與排錯 Q&A

Q1:為什麼在程式碼裡直接寫 const num = 00123 會報錯或數值變掉?

  • 問題原因:在 JavaScript 中,數字字面量(Numeric Literal)若以 0 開頭(如 0123),在非嚴格模式下會被當成八進位(Octal)解析(0123 會變成十進位的 83),而在嚴格模式('use strict')下則會直接拋出 SyntaxError。
  • 解決思路:前導零只存在於**字串型別(String)**中,儲存或顯示前導零時請一律使用字串(如 "00123")。

Q2:遇到負數(如 -5)呼叫 String(-5).padStart(4, '0') 為什麼會變成 "00-5"?

  • 問題原因:String(-5) 轉為字串後是 "-5",padStart 只負責在整個字串的最左邊補 '0',不會自動跳過負號。
  • 解決思路:若需處理負數前導零,可先取絕對值 Math.abs(n) 補零後,再根據 n < 0 補回負號:
    const formatSignedZero = (n, len) => (n < 0 ? '-' : '') + String(Math.abs(n)).padStart(len, '0');
    console.log(formatSignedZero(-5, 3)); // 輸出: "-005"

參考資料與延伸閱讀

10 留言

  1. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  2. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  3. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  4. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  5. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  6. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  7. Reading your article has greatly helped me, and I agree with you. But I still have some questions. Can you help me? I will pay attention to your answer. thank you.

  8. Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!

發表迴響