Adding zero to non leaded zero datetime string regex

48 views Asked by At

I have the following datetime string 2020-5-1 1:2 I used the pattern (\W)(\d{1}) to match any digit with length 1 i.e non zero leaded, 5,1,1,2. This demo shows that pattern succeeded to catch them in the group 2 for every match.

Using Javascript's String replace method, I have tried to turn the datetime sample string to be 2020-05-01 01:02. In this jsbin that runs the following snippet:

var txt = '2020-5-1 1:2'
var output = [];
output[0] = txt.replace(/(\W)(\d{1})/gi,'0$1');
output[1] = txt.replace(/(\W)(\d{1})/gi,'0$2');
console.log(output);
// The output: ["20200-0-0 0:", "202005010102"]

In the first output's entry, it does unexpected behavior, instead of adding 0 to the match, it replaced it with 0! How could I solve this issue?

1

There are 1 answers

0
Wiktor Stribiżew On BEST ANSWER

You only used a single placeholder in the replacement pattern, but in the regex pattern, you consumed two substrings with two capturing groups, so one is lost.

To add 0 before single digits you may use

txt.replace(/\b\d\b/g,'0$&')
txt.replace(/(^|\D)(\d)(?!\d)/g,'$10$2')
txt.replace(/(?<!\d)\d(?!\d)/g,'0$&')     // With the ECMAScript2018+

Here, \b\d\b matches a digit that is neither preceded nor followed with an ASCII letter, digit or _. The substitution is 0 and the whole match value, $&.

The (^|\D)(\d)(?!\d) pattern capture start of string or a non-digit char into Group 1, then a digit is captured in Group 2. Then, (?!\d) makes sure there is no digit immediately to the right. The substitution is $10$2, Group 1 value, 0 and then Group 2 value.

The (?<!\d)\d(?!\d) pattern matches any digit not enclosed with other digits, and the substitution is the same as in Case 1.

JS demo:

var txt = '2020-5-1 1:2';
console.log( txt.replace(/\b\d\b/g,'0$&') )
console.log( txt.replace(/(^|\D)(\d)(?!\d)/g,'$10$2') )