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

如何用Node.js正则表达式批量修改HTML img标签并写入文件?

解决Node.js批量修改HTML img标签的问题

Got it, let's fix this up for you. You want to add the img-responsive class and sequentially numbered IDs (from scene_1 to scene_141) to all those <img src="img/sceneX.jpg"> tags in your HTML file. Here's a complete, tested solution using Node.js's fs module and regular expressions:

Step-by-Step Code Implementation

First, make sure you have a backup of your original HTML file (always a good practice before batch modifications!). Then use this script:

const fs = require('fs');
const path = require('path');

// Replace with your actual HTML file path
const targetHtmlFile = path.join(__dirname, 'your-target-file.html');

// Initialize our ID counter starting at 1
let currentSceneId = 1;

// Read the HTML file
fs.readFile(targetHtmlFile, 'utf8', (readErr, htmlContent) => {
  if (readErr) {
    console.error('Failed to read the HTML file:', readErr);
    return;
  }

  // Use regex to match and replace each target img tag
  const updatedHtml = htmlContent.replace(
    /<img src="(img\/scene\d+\.jpg)"/g,
    (matchedTag, capturedSrc) => {
      // Only increment up to scene_141
      if (currentSceneId > 141) return matchedTag;
      
      const updatedTag = `<img src="${capturedSrc}" class="img-responsive" id="scene_${currentSceneId}">`;
      currentSceneId++;
      return updatedTag;
    }
  );

  // Write the modified content back to the file
  fs.writeFile(targetHtmlFile, updatedHtml, 'utf8', (writeErr) => {
    if (writeErr) {
      console.error('Failed to write the updated HTML file:', writeErr);
      return;
    }
    console.log(`Success! Updated ${currentSceneId - 1} img tags with class and sequential IDs.`);
  });
});

Key Details Explained

  • Regex Pattern: /<img src="(img\/scene\d+\.jpg)"/g

    • The g flag ensures we match all instances of the tag, not just the first one.
    • The parentheses capture the src attribute value (like img/scene1.jpg) so we can reuse it in the replacement.
  • Replacement Callback:

    • We use a callback function instead of a static string replacement to dynamically generate the incrementing ID.
    • We added a check to stop incrementing once we hit scene_141, so any extra matching tags (if present) won't get invalid IDs.
  • File Handling:

    • We use fs.readFile to load the HTML content as a UTF-8 string, process it, then fs.writeFile to save the changes back to the original file (or you can change the path to write to a new file if you prefer).

Notes

  • If your HTML file is very large, consider using Node.js streams (fs.createReadStream and fs.createWriteStream) to avoid loading the entire file into memory at once.
  • Double-check your regex if your img tags have any extra whitespace or attributes (the pattern assumes tags are exactly like <img src="img/sceneX.jpg"> with no other attributes).

内容的提问来源于stack exchange,提问作者Zichen Ma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:27:02