日期字符串正则替换异常:需将-替换为%2d、:替换为%3a的需求实现
Got it, let's sort out this regex replacement issue for you! The problem here is that your current regex is incorrectly replacing hyphens (-) with %3a (the URL encoding for colons) instead of %2d (the encoding for hyphens). Let's break down the solutions:
Option 1: Two Separate Replacements (Simple & Straightforward)
The easiest way to avoid mixing up the characters is to handle hyphens and colons in two distinct steps. This is less error-prone than trying to do it in one regex pass:
const originalDate = "2018-04-18T00:00:00"; // First replace hyphens with %2d, then colons with %3a const encodedDate = originalDate.replace(/-/g, "%2d").replace(/:/g, "%3a"); console.log(encodedDate); // Outputs: 2018%2d04%2d18T00%3a00%3a00
This works because we're explicitly targeting each character type separately—no chance of mixing up the replacement values.
Option 2: Single Regex with Callback Function (One-Pass Processing)
If you prefer to handle everything in a single regex operation, you can match both characters and use a callback to return the correct encoding based on which character was matched:
const originalDate = "2018-04-18T00:00:00"; const encodedDate = originalDate.replace(/[-:]/g, (match) => { return match === "-" ? "%2d" : "%3a"; }); console.log(encodedDate); // Outputs the desired result
The regex [-:] matches either a hyphen or a colon. The callback checks which character was captured and returns the corresponding URL-encoded string.
Why Your Original Regex Failed
It sounds like your initial regex was either replacing all matched characters with %3a (including hyphens) or had the replacement logic reversed. By separating the operations or using a conditional callback, we ensure each character gets mapped to the correct encoding.
内容的提问来源于stack exchange,提问作者MokiNex

