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

如何用JavaScript为多张图片URL插入当前日期

批量替换图片URL中的日期为当前日期(JavaScript实现)

实现思路

核心分为两步:生成YYYY/MM/DD格式的当前日期字符串,再批量遍历页面中的图片元素,替换URL里的旧日期段。

具体代码实现

// 生成格式为 YYYY/MM/DD 的当前日期
function getCurrentFormattedDate() {
  const today = new Date();
  const year = today.getFullYear();
  // 月份从0开始,需+1后补零到两位
  const month = String(today.getMonth() + 1).padStart(2, '0');
  // 日期补零到两位
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}/${month}/${day}`;
}

// 批量更新所有图片的URL日期
function updateImageDates() {
  const currentDate = getCurrentFormattedDate();
  // 获取页面所有img元素,如需指定范围可修改选择器,比如 '.target-imgs img'
  const images = document.querySelectorAll('img');
  
  images.forEach(img => {
    // 方式1:用正则匹配任意YYYY/MM/DD格式的日期段并替换(通用场景)
    img.src = img.src.replace(/\d{4}\/\d{2}\/\d{2}/, currentDate);
    
    // 方式2:直接替换固定旧日期(已知旧日期的场景,性能更优)
    // img.src = img.src.replace('2023/01/08', currentDate);
  });
}

// 页面加载完成后执行替换
window.addEventListener('load', updateImageDates);

代码说明

  • getCurrentFormattedDate:确保生成的日期始终是两位月份和日期,避免出现2024/1/5这类不统一的格式。
  • updateImageDates:
    • 若只需处理特定图片,可给目标图片添加统一class,修改querySelectorAll的选择器(比如document.querySelectorAll('.date-update-img'))。
    • 两种替换方式可按需选择:正则匹配适合日期不固定的场景,固定字符串替换适合已知旧日期的场景。
  • 绑定load事件是为了确保页面所有图片元素加载完成后再执行操作,避免出现找不到元素的问题。

内容的提问来源于stack exchange,提问作者Dhiraz Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:41:19