这个
$<day>
命名的反向引用只能在字符串替换模式中使用。由于需要修改捕获,因此需要使用匿名方法:
.replace(regex, (_,month,day,year) => `${pad(month)}`)
这里,在括号中,您必须为整个匹配和捕获组定义变量。因此,基本上,您不需要新的ECMAScript 2018 regex增强功能,因为这里也可以使用常规编号的捕获组。
查看更新的演示:
const pad = date => date.length === 2 ? date : '0' + date;
const normalizeDate = date => {
const regex = /(?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4})/;
// pad string of length 1 works correctly (expected '01'/ result '01')
console.log(date.replace(regex, (_,month,day,year) => pad(month)));
// pad sting of length 2 doesn't (expected '12' / result '012')
console.log(date.replace(regex, (_,month,day,year) => pad(day)));
// test shows that <day> = 12
console.log(date.replace(regex, "$<day>"));
// padding 12 directly works (expected '12' / result '12')
console.log(pad('12'));
return date.replace(regex, (_,month,day,year) => `${pad(month)}-${pad(day)}-${year}`);
}
const date = '1/12/2014';
console.log(normalizeDate(date));