简体   繁体   English

RegEx在JavaScript中拆分格式字符串

[英]RegEx to split formatting string in JavaScript

I am using a JS date library which has a simple asString() formatting syntax eg dd mmm yyyy produces 01 Jan 1970 . 我正在使用具有简单asString()格式语法的JS日期库,例如dd mmm yyyy产生01 Jan 1970

Unfortunately should the month happen to contain a letter that appears in the formatting string it can go wrong, eg `Date('2014-09-01').asString('dd mmm yyyy') = 01 Septe9ber 2014' 不幸的是,如果月份恰好包含一个出现在格式字符串中的字母,则可能会出错,例如`Date('2014-09-01')。asString('dd mmm yyyy')= 2014年9月9日'

To solve this is quite simple; 解决这个问题很简单; alter the asString() method to use the format '[dd] [mmm] [yyyy]' instead. 更改asString()方法以改为使用格式[[dd] [mmm] [yyyy]'。 However this comes from a global format string used by other methods. 但是,这来自其他方法使用的全局格式字符串。 The only method that needs the square brackets is the asString method. 唯一需要方括号的方法是asString方法。

So my ideal solution is to simply add a function in that method which replaces any of the following strings within the format string: 因此,我的理想解决方案是在该方法中简单地添加一个函数,以替换format字符串中的以下任何字符串:

formats=['yyyy','yy','mmmm','mmm','mm','m','dddd','ddd','dd','d','hh','min','ss'];

With itself surrounded by [] []包围

dd/mm/yyyy => [dd]/[mm]/[yyyy]

Unfortunately the RegEx is proving to be complex - simply looping through each item results in [[d][d]]/[[m][m]]/[[yy][yy]] . 不幸的是,正则表达式证明很复杂-简单地遍历每个项目会导致[[d][d]]/[[m][m]]/[[yy][yy]]

So I'd like help writing this RegEx. 因此,我需要帮助编写此RegEx。 If it can't be done please say so - I'm not interested in using new libraries as a solution but would consider solutions which solved the problem in a different way within the current asString method (ie no breaking changes) 如果无法完成,请这样说-我对使用新库作为解决方案不感兴趣,但会考虑在当前的asString方法中以不同方式解决问题的解决方案(即无重大更改)

This should do: 应该这样做:

var regex = /(min|y+|m+|d+|h+|s+)/g,
    newString = format.replace(regex,'[$1]');

Tested with the format "dd/mm/yyyy" , resulted in "[dd]/[mm]/[yyyy]" 经过格式"dd/mm/yyyy" ,结果为"[dd]/[mm]/[yyyy]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM