簡體   English   中英

將模板文字內部的正則表達式組捕獲為函數參數

[英]Capturing regex group inside of template literal as function argument

我有一組采用一種格式的日期,我需要將這些日期轉換為另一種格式。

輸入: <month>/<day>/<year>

輸出: <day>/<month>/<year> -另外,如果月份和日期僅包含一個字符,則需要用0填充月份和日期。

我創建了正則表達式以匹配給定的日期格式。 然后,我想使用String.prototype.replace修改該日期,並通過將捕獲的組直接傳遞給模板文字內部的函數作為replace方法的第二個參數來修改捕獲的組。

我面臨的問題是,它無法正常運行。 在某些情況下,Function pad正確pad日期,而在其他情況下則不能。 更准確地說,我希望第二個控制台日志為12 ,但結果為012

 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, `${pad('$<month>')}`)); // pad sting of length 2 doesn't (expected '12' / result '012') console.log(date.replace(regex, `${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, `${pad('$<month>')}-${pad('$<day>')}-$<year>`); } const date = '1/12/2014'; normalizeDate(date); 

有人知道該代碼有什么問題嗎?

$<day>命名的反向引用只能在字符串替換模式中使用。 由於需要修改捕獲,因此需要使用匿名方法:

.replace(regex, (_,month,day,year) => `${pad(month)}`)

在這里,必須在括號中定義整個匹配項和捕獲組的變量。 因此,基本上不需要新的ECMAScript 2018正則表達式增強功能,因為您也可以在此處使用常規編號的捕獲組。

請參閱更新的演示:

 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)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM