You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FreeCodeCamp时间戳API项目:正则表达式导致输出异常问题

问题:FreeCodeCamp时间戳API项目正则表达式验证错误

我正在完成FreeCodeCamp的时间戳API项目,之前用Moment.js验证输入时间,功能正常但怀疑它导致项目无法通过考核,于是改用正则表达式,结果现在输出结果错误。

以下是基于Replit用Node.js和Express开发的当前代码:

// index.js
// where your node app starts

// init project
var express = require('express');
var moment = require('moment');
var app = express();

// enable CORS (https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
// so that your API is remotely testable by FCC 
var cors = require('cors');
app.use(cors({optionsSuccessStatus: 200}));  // some legacy browsers choke on 204

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (req, res) {
  res.sendFile(__dirname + '/views/index.html');
});

// your first API endpoint... 
app.get("/api/hello", function (req, res) {
  res.json({greeting: 'hello API'});
});

app.get("/api/:date?", function (req, res) {
 // Check if the entered param format is correct
  std = moment(req.params.date, 'YYYY-MM-DD', true).isValid()
  un = moment.unix(req.params.date, true).isValid()

  //Validation

  //Handling Standard Date Parameters:
  let stdDate = new Date(req.params.date);
  let unix_std = stdDate.getTime()
  let utc_std = stdDate.toUTCString()
  
  //Handling Millisecond Date Parameters:
  let milliDate = new Date(parseInt(req.params.date));
  let unix_milli = milliDate.getTime()
  let utc_milli = milliDate.toUTCString()

  //Handling Empty Date Parameters:
  let emptyDate = new Date();
  let unix_empty = emptyDate.getTime()
  let utc_empty = emptyDate.toUTCString()
  

  regex_std = /\d{4}-\d{2}-\d{2}/gm
  regex_un = /\d{0,}/gm
  //console.log(regex_std.test(req.params.date))
  //console.log(regex_un.test(req.params.date))
  
  if (regex_std) {
    console.log('Valid STD Date!!')
    res.json({unix: unix_std, utc: utc_std})
  } else if (regex_un) {
    console.log('Valid UN Date!!')
    res.json({unix: unix_milli, utc: utc_milli})
  } else if (req.params.date == null) {
    console.log("Empty Date")
    res.json({unix: unix_empty, utc: utc_empty})
  } else {
    console.log('Try again :(')
    res.json({ error : "Invalid Date" })
  }
});



// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
});

// Receive request with date in url, read url, validate date, conver to unix and utc, send to re.json using req.queury.unix/utc

问题分析与修复方案

你的正则逻辑存在几个关键错误:

  1. 正则判断方式错误:if (regex_std) 只是检查正则表达式本身是否存在,永远为true,正确做法是用regex_std.test(req.params.date)来测试输入参数是否匹配格式
  2. unix时间正则无效:/\d{0,}/gm会匹配空字符串或任意数字组合,应该用/^\d+$/匹配纯数字(至少1位),同时去掉全局模式gm(单次测试不需要)
  3. 判断顺序错误:空参数的判断应该放在最前面,否则会被前面的正则判断拦截
  4. 缺少日期有效性验证:用new Date()处理后需要检查是否为有效日期(比如stdDate.toString() !== 'Invalid Date'或者!isNaN(unix_std))

修正后的代码

app.get("/api/:date?", function (req, res) {
  const dateParam = req.params.date;

  // 处理空参数:返回当前时间
  if (!dateParam) {
    const now = new Date();
    console.log("Empty Date");
    return res.json({ unix: now.getTime(), utc: now.toUTCString() });
  }

  // 正则定义:匹配YYYY-MM-DD格式
  const regexStd = /^\d{4}-\d{2}-\d{2}$/;
  // 匹配纯数字(unix毫秒时间戳)
  const regexUnix = /^\d+$/;

  // 处理标准日期格式
  if (regexStd.test(dateParam)) {
    const stdDate = new Date(dateParam);
    if (!isNaN(stdDate.getTime())) {
      console.log('Valid STD Date!!');
      return res.json({ unix: stdDate.getTime(), utc: stdDate.toUTCString() });
    }
  }

  // 处理unix毫秒时间戳
  if (regexUnix.test(dateParam)) {
    const milliDate = new Date(parseInt(dateParam));
    if (!isNaN(milliDate.getTime())) {
      console.log('Valid UN Date!!');
      return res.json({ unix: milliDate.getTime(), utc: milliDate.toUTCString() });
    }
  }

  // 无效日期
  console.log('Try again :(');
  res.json({ error: "Invalid Date" });
});

关键修改说明

  • 调整判断顺序,优先处理空参数
  • 修正正则表达式的匹配逻辑,使用test()方法验证输入
  • 添加日期有效性检查,避免返回无效日期的结果
  • 用const定义常量,提升代码可读性和稳定性

内容的提问来源于stack exchange,提问作者Demi Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:05:02