[英]Javascript regex for formatting time
Our organization's style guide specifies a date-time in this format: Dec. 31 08:45 am
.我们组织的样式指南以这种格式指定了日期时间:
Dec. 31 08:45 am
。 Our site runs Drupal, which is a PHP-based CMS.我们的网站运行 Drupal,这是一个基于 PHP 的 CMS。 Its field formatting templates allow for date-formatting strings specified in the encoding which is defined in HPHP's
date()
function.它的字段格式模板允许在 HPHP 的
date()
函数中定义的编码中指定日期格式字符串。 It only offers a
, which gives pm
, and A
, which gives me PM
, but I don't see anything specifying one with periods.它只提供
a
,它给出pm
,而A
给出我PM
,但我没有看到任何指定一个句点的东西。
Unfortunately, there is not an easy way to hook in to the platform to define a custom date format, so I figure the simplest way forward is to do a find-and-replace with javascript.不幸的是,没有一种简单的方法可以连接到平台来定义自定义日期格式,所以我认为最简单的方法是使用 javascript 进行查找和替换。 What I want to do is replace instances in the format
NN:NN am
and NN:NN pm
with NN:NN am
, etc.我想要做的就是在格式取代实例
NN:NN am
和NN:NN pm
与NN:NN am
,等
Regexes have never been my strong suit.正则表达式从来都不是我的强项。 I can match date time format well enough(
[0-9][0-9]:[0-9][0-9] pm
), but I don't know how to perform the proper replacement.我可以很好地匹配日期时间格式(
[0-9][0-9]:[0-9][0-9] pm
),但我不知道如何执行正确的替换。
How can I replace am
and pm
with properly abbreviated version, when they follow a four-digit time format?当
am
和pm
遵循四位时间格式pm
,如何用正确的缩写版本替换它们?
An alternative is using the optional handler in the function replace
to get the match string and replace the am
or pm
strings with am
or pm
respectively.另一种方法是使用函数
replace
的可选处理程序来获取匹配字符串,并分别用am
或pm
替换am
或pm
字符串。
let str = "Dec. 31 08:45 am", result = str.replace(/([\\d][\\d]:[\\d][\\d] am|pm)/, function(match) { return match.replace('am', 'am').replace('pm', 'pm'); }); console.log(result);
str.replace(/(\d{2}:\d{2}\s?a|p)(m)/, '$1.$2');
You can use the following regex and replacement pattern to do, what you want:您可以使用以下正则表达式和替换模式来执行您想要的操作:
Regex: ([0-2][0-9]:[0-5][0-9]\\s)(a|p)(m)
正则表达式:
([0-2][0-9]:[0-5][0-9]\\s)(a|p)(m)
Replace: '$1$2.$3.'替换:'$1$2.$3。'
How to use:如何使用:
var text = 'Dec. 31 08:45 am';
text = text.replace(/([0-2][0-9]:[0-5][0-9] )(a|p)(m)/, '$1$2.$3.');
'Dec. 31 08:45 AM, Jan. 1 10:15 pm'.replace(/(\d{2}:\d{2}) (a|p)(m)/ig, (match, p1, p2, p3) => {
return `${p1} ${p2}.${p3}.`.toLowerCase();
});
yields the result产生结果
Dec. 31 08:45 a.m., Jan. 1 10:15 p.m.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.