欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > 解锁 indexOf、substring 和 JSON.stringify:从小程序图片上传看字符串魔法 ✨

解锁 indexOf、substring 和 JSON.stringify:从小程序图片上传看字符串魔法 ✨

2025/3/9 21:31:51 来源:https://blog.csdn.net/m0_65152767/article/details/145951808  浏览:    关键词:解锁 indexOf、substring 和 JSON.stringify:从小程序图片上传看字符串魔法 ✨

🌟 解锁 indexOfsubstringJSON.stringify:从小程序图片上传看字符串魔法 ✨

在 JavaScript 中,字符串操作和数据序列化是开发中不可或缺的技能。indexOfsubstringJSON.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)});});
};

我们将聚焦 productPhotospurchaseRecords 的处理,分析 indexOfsubstringJSON.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 到路径

🎯 操作流程

  1. 输入data.productImages = ["https://example.com/path/to/image1.jpg", "https://example.com/path/to/image2.jpg"]
  2. indexOf:定位每个 URL 的路径起点。
    • "https://example.com/path/to/image1.jpg" -> pathStart = 19
  3. substring:提取路径。
    • url.substring(20) -> "path/to/image1.jpg"
  4. 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);
    

🎁 总结

indexOfsubstringJSON.stringify 是字符串处理与数据序列化的黄金组合:

  • indexOf 精准定位,解析 URL 结构。
  • substring 灵活裁剪,提取关键信息。
  • JSON.stringify 完美打包,适配后台。

在小程序图片上传中,三者协作将复杂 URL 转为简洁路径,展现了 JavaScript 的强大能力。试试这些方法,优化你的数据处理吧!


在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词