NodeJS处理特定格式字符串,按商品数量批量发送对应邮件
Got it, let's work through this problem step by step—here's how you can parse that string and send the required emails in Node.js:
Step 1: Clean & Split the Raw String
First, we need to fix the HTML-encoded & to plain &, then split the string into individual package groups using the ? separator. We'll also filter out any empty entries since your string ends with a trailing ?.
Step 2: Convert Groups to Structured Objects
Turn each string group (like "Package=Package Two&Qty=3&Price=702") into a readable JavaScript object, making sure to convert Qty and Price to numbers (not strings) for easier handling.
Step 3: Send Emails Based on Quantity
Loop through each package, then repeat the email send process Qty number of times, including the package name and price in each email.
Full Code Example
// Replace this with your actual email sending logic (e.g., using nodemailer/SendGrid) const sendEmail = async (packageName, price) => { // Simulate async email send delay await new Promise(resolve => setTimeout(resolve, 100)); console.log(`✅ Sent email for: *${packageName}* | Price: $${price}`); }; const processPackageData = async (inputString) => { // Step 1: Clean the string and split into package groups const cleanedString = inputString.replace(/&/g, '&'); const packageGroups = cleanedString.split('?').filter(group => group.trim() !== ''); // Step 2: Convert each group to a structured object const packages = packageGroups.map(group => { const params = new URLSearchParams(group); return { name: params.get('Package'), quantity: parseInt(params.get('Qty'), 10), price: parseInt(params.get('Price'), 10) }; }); // Step 3: Send emails for each quantity for (const pkg of packages) { for (let i = 0; i < pkg.quantity; i++) { await sendEmail(pkg.name, pkg.price); } } }; // Your input string const rawInput = "Package=Package&Qty=1&Price=123?Package=Package Two&Qty=3&Price=702?Package=Package Three&Qty=1&Price=199?Package=Package One&Qty=4&Price=852?"; // Run the process processPackageData(rawInput) .then(() => console.log('\nAll emails sent successfully!')) .catch(err => console.error('❌ Error sending emails:', err));
Quick Notes:
- URLSearchParams: This built-in Node.js API takes care of parsing key-value pairs without messy manual string splitting.
- Async/Await: Email sending is almost always asynchronous, so we use async/await to ensure we don't skip any emails or run into race conditions.
- Email Integration: Swap the
sendEmailfunction with your actual email service code—for example, usingnodemailerwith an SMTP server, or a managed service like SendGrid/Mailgun.
内容的提问来源于stack exchange,提问作者NewUser

