如何用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
gflag ensures we match all instances of the tag, not just the first one. - The parentheses capture the
srcattribute value (likeimg/scene1.jpg) so we can reuse it in the replacement.
- The
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.readFileto load the HTML content as a UTF-8 string, process it, thenfs.writeFileto save the changes back to the original file (or you can change the path to write to a new file if you prefer).
- We use
Notes
- If your HTML file is very large, consider using Node.js streams (
fs.createReadStreamandfs.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
相关产品推荐
相关产品推荐

