[英]How to format string to mm/dd/yyyy with regex
I have been struggling with this particular regular expression and was wondering if anyone can help. 我一直在努力使用这种特殊的正则表达式,并且想知道是否有人可以提供帮助。 I have an input field that allows users to enter text and if a user enters 01201990 I have a method that converts it to 01/20/19/90 The problem is I don't want the regular expression to continue after the mm/dd/ my end result would look like this 01/20/1990 Any help would be amazing.
我有一个输入字段,允许用户输入文本,如果用户输入01201990,我有一种将其转换为01/20/19/90的方法。问题是我不希望在mm / dd之后继续使用正则表达式/我的最终结果将如下所示: 1990年1月20日任何帮助都将是惊人的。
var tmparray = [];
tmparray.push(
tmp.model
// here is where I dont know how to prevent the regex
// from continuing after 01/20/
.match(new RegExp('.{1,2}', 'g'))
.join("/")
);
tmp.model = tmparray;
console.log(tmp.model);
You can use replace()
in this case 您可以在这种情况下使用
replace()
document.write('19101992'.replace(/(\\d{2})(\\d{2})(\\d{4})/, '$1/$2/$3'))
Your code will be like 您的代码将像
var tmparray = [];
tmparray.push(
tmp.model
// here is where I dont know how to prevent the regex
// from continuing after 01/20/
.replace(/(\d{2})(\d{2})(\d{4})/g, '$1/$2/$3')
);
tmp.model = tmparray;
console.log(tmp.model);
why not just match on: /(\\d{2})(\\d{2})(\\d{4})/ 为什么不匹配:/(\\ d {2})(\\ d {2})(\\ d {4})/
then dd/mm/yyyy is: $1/$2/$3 那么dd / mm / yyyy是:$ 1 / $ 2 / $ 3
(I can't see why you'd match {1,2} since you can't tell the difference between 1/11/1990 and 11/1/1990 and in either case would get 11/11/990...) (我看不到为什么要匹配{1,2},因为您无法分辨1990年1月11日与1990年11月1日之间的区别,无论哪种情况都将得到11/11/990 ... )
Try using String.prototype.slice()
, String.prototype.concat()
尝试使用
String.prototype.slice()
, String.prototype.concat()
var str = "01201990" , d = "/" , res = str.slice(0,2).concat(d + str.slice(2,4)).concat(d + str.slice(4)); console.log(res)
use regex [0-9]{2}(?=(?:[0-9]{4})). 使用正则表达式[0-9] {2}(?=(?:[0-9] {4}))。 for more information please check link https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch06s12.html
有关更多信息,请检查链接https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch06s12.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.