JS Regex:如何从“08/08/2017”中删除前 2 个零

JS Regex: how to remove first 2 zero's from "08/08/2017"

我是正则表达式的新手,整晚都在研究如何从“08/08/2017”这样的字符串中删除前 2 个零(不删除“2017”中的 0)

我看过的 5 多个正则表达式教程似乎没有涵盖我在这里需要的内容。

日期可以是系统返回的任何系统日期。所以正则表达式也需要为“12/12/2017”工作

这是我想到的最好的:

let sysdate = "08/08/2017"
let todayminuszero = str.replace("0","");
let today = todayminus0.replace("0","");

能用,但明显不专业

根据教程,我很确定我可以按照以下方式做一些事情: str.replace(/\d{2}//g,""),); 这种模式将避免在 str 中得到第三个零。 替换字符串必须指示 8/8/ 不过不知道怎么写。

对于日期操作,我会使用其他函数(最佳日期相关)但是,对于您所说的情况,这应该可以做到。如果您需要其他格式,我建议您以不同的方式删除零,但这完全取决于您的用例。

let sysdate = "08/08/2017";
let todayminuszero = sysdate.replace(/0(?=\d\/)/gi,"");
console.info(todayminuszero);

(?= ... ) is called Lookahead and with this you can see what is there, without replacing it
in this case we are checking for a number and a slash. (?=\d\/) here some more information, if you want to read about lookahead and more http://www.regular-expressions.info/lookaround.html

测试正则表达式的好地方是https://regex101.com/ 我总是将它用于更高级的表达式,因为它会显示所有匹配的组,并提供很好的解释。很棒 resource/help,如果您正在学习或创建困难的表达式。

Info: as mentioned by Rajesh, the i flag is not needed for this Expression, I just use it out of personal preference. This flag just sets the expression-match to case insensitive.

-- 超出范围,但可能很有趣--

没有正则表达式的更长的解决方案可能如下所示:

let sysdate = "08/08/2017";
let todayminuszero = sysdate.split("/").map(x => parseInt(x)).join("/");

console.info(todayminuszero);

背面,这个解决方案有很多移动部分,split 函数创建一个数组(´"08/08/2017"´ to ´["08", "08", "2017"] ´),map 函数,带有 lambda 函数 =>parseInt 函数,使每个字符串项成为一个漂亮的整数(例如:"08"8, ... ) 最后是 join 函数,它从新创建的整数数组中创建最终字符串。

前 2 个零,我理解你的意思是 8 之前的月份和日期为零。

您可以尝试这样的操作:

想法

  • 创建一个正则表达式来捕获代表日期、月份和年份的数字组。
  • 使用此正则表达式替换值。
  • 使用函数 return 处理值。

var sysdate = "08/08/2017"
var numRegex = /(\d)+/g;

var result = sysdate.replace(numRegex, function(match){
  return parseInt(match)
});
console.log(result)

你应该使用这个

let sysdate = "08/08/2017"
let todayminuszero = sysdate.replace(/(^|\/)0/g,"");
console.log(todayminuszero);

function stripLeadingZerosDate(dateStr){
    return dateStr.split('/').reduce(function(date, datePart){
        return date += parseInt(datePart) + '/'
    }, '').slice(0, -1);
}

console.log(stripLeadingZerosDate('01/02/2016'));
console.log(stripLeadingZerosDate('2016/02/01'));

看这里

function stripLeadingZerosDate(dateStr){
return dateStr.split('/').reduce(function(date, datePart){
    return date += parseInt(datePart) + '/'
}, '').slice(0, -1);

}

console.log(stripLeadingZerosDate('01/02/2016'));// 1/2/2016
console.log(stripLeadingZerosDate('2016/02/01'));// "2016/2/1"