You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则匹配字符串末尾单个数字并通过$.replace()添加前导0?

Alright, let's figure out how to solve this problem where you need to add a leading zero to a single digit at the end of a string using regex and JavaScript's replace() (with jQuery-friendly options too).

Solution: Add Leading Zero to Trailing Single Digit

First, let's break down what we need to accomplish:

  • Target only the single digit sitting at the very end of a string
  • Replace that digit with 0 plus the original digit to get the desired formatted result

Step 1: The Right Regular Expression

We'll use this regex pattern for the basic case: /(\d)$/

  • \d: Matches any single numeric digit (0-9)
  • (): Wraps the digit in a capture group so we can reuse it in the replacement
  • $: Anchors the match to the end of the string, ensuring we only target the final character if it's a digit

If you want to avoid modifying digits that are part of a longer trailing number (e.g., leave "test12" alone but modify "test5"), use a negative lookbehind to ensure no digit precedes the trailing digit: /(?<!\d)(\d)$/

Step 2: Using replace() (Raw Strings + jQuery DOM Elements)

For raw string manipulation:

jQuery doesn't have a standalone $.replace() function, but JavaScript's native String.replace() works perfectly here:

// Example input string
const originalStr = "test5";
// Run the replacement
const modifiedStr = originalStr.replace(/(\d)$/, "0$1");
console.log(modifiedStr); // Output: "test05"
  • $1 in the replacement string refers directly to the digit we captured with the parentheses in our regex—this lets us keep the original digit while adding the leading zero.

For updating text in jQuery DOM elements:

If you need to modify text inside HTML elements, use jQuery's .text() method with a callback to process each element's content:

// Update all elements with the class "target-text"
$(".target-text").text(function(index, currentText) {
  return currentText.replace(/(\d)$/, "0$1");
});

Quick Edge Case Notes

  • If your string ends with multiple digits (e.g., "test12"), the basic regex will add a zero only to the final digit, resulting in "test102". Use the negative lookbehind version if you want to skip these cases.
  • If the string doesn't end with a digit, replace() will leave it completely unchanged—no extra conditional checks needed!

内容的提问来源于stack exchange,提问作者Richard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:52:59