🌟 解锁 indexOf、substring 和 JSON.stringify:从小程序图片上传看字符串魔法 ✨
在 JavaScript 中,字符串操作和数据序列化是开发中不可或缺的技能。indexOf、substring 和 JSON.stringify 是三个简单却强大的工具,分别用于定位子字符串、提取片段和将对象转为 JSON 字符串。今天,我们将以一个微信小程序的图片上传功能为例,深入探索这三个方法如何协作处理图片 URL,确保数据高效传递到后台。
本文从实践出发,带你领略字符串操作的魅力!
🎬 示例场景:小程序图片上传
我们开发一个微信小程序,用户上传产品照片后,数据通过 saveFakeRegistration 函数保存到后台。以下是关键代码:
/**
* 保存/修改假货登记
* @param {Object} data - 要保存的假货登记数据
* @param {Boolean} isSubmit - 是否为提交线上协助比对 (true: 提交, false: 暂存)
* @returns {Promise} 请求结果的Promise
*/
const saveFakeRegistration = (data, isSubmit = false) => {
const sessionId = wx.getStorageSync('sessionId');
const adminToken = wx.getStorageSync('admin_token');
const inviteCodeId = wx.getStorageSync('inviteCodeId');
const fakeRegistration = {
...(data.id ? { id: data.id } : {}),
productName: data.productName,
productId: data.productId,
purchaseChannel: data.channel || '',
purchasePrice: data.price || '',
contactInfo: data.contact || '',
productPhotos: JSON.stringify((data.productImages || []).map(url => {
const pathStart = url.indexOf('/', url.indexOf('//') + 2);
return pathStart !== -1 ? url.substring(pathStart + 1) : url;
})),
purchaseRecords: JSON.stringify((data.purchaseRecords || []).map(url => {
const pathStart = url.indexOf('/', url.indexOf('//') + 2);
return pathStart !== -1 ? url.substring(pathStart + 1) : url;
})),
inviteCodeId: inviteCodeId,
comparisonStatus: isSubmit ? 1 : 0
};
return new Promise((resolve, reject) => {
wx.request({
url: `${path.BASE_API_URL}/fakeRegistration/registration/save`,
method: 'POST',
data: fakeRegistration,
header: {
'content-type': 'application/json',
'token': adminToken,
'Cookie': sessionId
},
success: (res) => {
if (res.data.code === 0) resolve(res.data);
else reject(new Error(res.data.msg || '保存失败'));
},
fail: (error) => reject(error)
});
});
};
我们将聚焦 productPhotos 和 purchaseRecords 的处理,分析 indexOf、substring 和 JSON.stringify 如何将图片 URL 转为后台所需的格式。
🔍 认识 indexOf:定位大师
🌟 定义
indexOf 是字符串方法,用于查找子字符串第一次出现的位置。
🌈 语法
string.indexOf(searchValue[, fromIndex])
- 返回值:索引(找到)或
-1(未找到)。
🎨 在代码中的应用
const pathStart = url.indexOf('/', url.indexOf('//') + 2);
- 嵌套使用:
url.indexOf('//'):找到协议后的双斜杠(如https://中的//)。url.indexOf('/', url.indexOf('//') + 2):从双斜杠后开始,找下一个斜杠(路径起点)。
🎉 示例
const url = "https://example.com/path/to/image.jpg";
const doubleSlash = url.indexOf('//'); // 6
const pathStart = url.indexOf('/', doubleSlash + 2); // 19
console.log(pathStart); // 19
💡 作用
- 定位 URL 中路径部分的起点(第三个斜杠),为后续提取做准备。
✂️ 认识 substring:裁剪专家
🌟 定义
substring 从字符串中提取指定范围的子字符串。
🌈 语法
string.substring(start[, end])
start:开始索引。end(可选):结束索引(不包含)。- 返回值:提取的子字符串。
🎨 在代码中的应用
return pathStart !== -1 ? url.substring(pathStart + 1) : url;
- 从第三个斜杠后(
pathStart + 1)提取路径,去掉前面的协议和域名。
🎉 示例
const url = "https://example.com/path/to/image.jpg";
const pathStart = 19;
const path = url.substring(pathStart + 1); // "path/to/image.jpg"
console.log(path);
💡 作用
- 提取图片的相对路径(如
"path/to/image.jpg"),确保数据简洁。
📦 认识 JSON.stringify:打包能手
🌟 定义
JSON.stringify 将 JavaScript 对象或数组转换为 JSON 字符串。
🌈 语法
JSON.stringify(value[, replacer[, space]])
value:要转换的值。- 返回值:JSON 格式的字符串。
🎨 在代码中的应用
productPhotos: JSON.stringify((data.productImages || []).map(url => {
const pathStart = url.indexOf('/', url.indexOf('//') + 2);
return pathStart !== -1 ? url.substring(pathStart + 1) : url;
})),
- 将处理后的路径数组转为 JSON 字符串。
🎉 示例
const images = ["https://example.com/img1.jpg", "https://example.com/img2.jpg"];
const paths = images.map(url => url.substring(url.indexOf('/', url.indexOf('//') + 2) + 1));
console.log(JSON.stringify(paths)); // '["img1.jpg", "img2.jpg"]'
💡 作用
- 将路径数组序列化为字符串,满足后台请求的格式。
🚀 三者的协作:从 URL 到路径
🎯 操作流程
- 输入:
data.productImages = ["https://example.com/path/to/image1.jpg", "https://example.com/path/to/image2.jpg"]。 indexOf:定位每个 URL 的路径起点。"https://example.com/path/to/image1.jpg"->pathStart = 19。
substring:提取路径。url.substring(20)->"path/to/image1.jpg"。
JSON.stringify:转为 JSON。["path/to/image1.jpg", "path/to/image2.jpg"]->'["path/to/image1.jpg","path/to/image2.jpg"]'。
🎨 结果
fakeRegistration.productPhotos:'["path/to/image1.jpg","path/to/image2.jpg"]'。- 发送到后台的数据简洁高效。
🌼 优化与思考
🎈 潜在问题
- 格式假设:代码假设 URL 均为
"协议://域名/路径",若格式异常(如无//),可能出错。 - 效率:嵌套
indexOf可读性稍低。
🎉 优化方案
- 正则替代:
productPhotos: JSON.stringify((data.productImages || []).map(url => url.replace(/^https?:\/\/[^/]+\//, ''))),- 更简洁,但需测试兼容性。
- 异常处理:
const pathStart = url.indexOf('/', url.indexOf('//') + 2); if (pathStart === -1) console.warn('Invalid URL:', url);
🎁 总结
indexOf、substring 和 JSON.stringify 是字符串处理与数据序列化的黄金组合:
indexOf精准定位,解析 URL 结构。substring灵活裁剪,提取关键信息。JSON.stringify完美打包,适配后台。
在小程序图片上传中,三者协作将复杂 URL 转为简洁路径,展现了 JavaScript 的强大能力。试试这些方法,优化你的数据处理吧!


















