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

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

在 JavaScript 中,字符串操作和数据序列化是开发中不可或缺的技能。indexOfsubstringJSON.stringify 是三个简单却强大的工具,分别用于定位子字符串、提取片段和将对象转为 JSON 字符串。今天,我们将以一个微信小程序的图片上传功能为例,深入探索这三个方法如何协作处理图片 URL,确保数据高效传递到后台。

本文从实践出发,带你领略字符串操作的魅力!


🎬 示例场景:小程序图片上传

我们开发一个微信小程序,用户上传产品照片后,数据通过 saveFakeRegistration 函数保存到后台。以下是关键代码:

javascript 复制代码
/**
 * 保存/修改假货登记
 * @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 是字符串方法,用于查找子字符串第一次出现的位置。

🌈 语法

javascript 复制代码
string.indexOf(searchValue[, fromIndex])
  • 返回值:索引(找到)或 -1(未找到)。

🎨 在代码中的应用

javascript 复制代码
const pathStart = url.indexOf('/', url.indexOf('//') + 2);
  • 嵌套使用
    • url.indexOf('//'):找到协议后的双斜杠(如 https:// 中的 //)。
    • url.indexOf('/', url.indexOf('//') + 2):从双斜杠后开始,找下一个斜杠(路径起点)。
🎉 示例
javascript 复制代码
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 从字符串中提取指定范围的子字符串。

🌈 语法

javascript 复制代码
string.substring(start[, end])
  • start:开始索引。
  • end(可选):结束索引(不包含)。
  • 返回值:提取的子字符串。

🎨 在代码中的应用

javascript 复制代码
return pathStart !== -1 ? url.substring(pathStart + 1) : url;
  • 从第三个斜杠后(pathStart + 1)提取路径,去掉前面的协议和域名。
🎉 示例
javascript 复制代码
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 字符串。

🌈 语法

javascript 复制代码
JSON.stringify(value[, replacer[, space]])
  • value:要转换的值。
  • 返回值:JSON 格式的字符串。

🎨 在代码中的应用

javascript 复制代码
productPhotos: JSON.stringify((data.productImages || []).map(url => {
  const pathStart = url.indexOf('/', url.indexOf('//') + 2);
  return pathStart !== -1 ? url.substring(pathStart + 1) : url;
})),
  • 将处理后的路径数组转为 JSON 字符串。
🎉 示例
javascript 复制代码
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 可读性稍低。

🎉 优化方案

  • 正则替代

    javascript 复制代码
    productPhotos: JSON.stringify((data.productImages || []).map(url => url.replace(/^https?:\/\/[^/]+\//, ''))),
    • 更简洁,但需测试兼容性。
  • 异常处理

    javascript 复制代码
    const pathStart = url.indexOf('/', url.indexOf('//') + 2);
    if (pathStart === -1) console.warn('Invalid URL:', url);

🎁 总结

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

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

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


相关推荐
Vic1010111 小时前
Hutool 的完整 JSON 工具类示例
开发语言·json
电商数据girl18 小时前
如何利用API接口与网页爬虫协同进行电商平台商品数据采集?
大数据·开发语言·人工智能·python·django·json
拷斤锟1 天前
使用Excel解析从OData API获取到的JSON数据
数据库·json·excel
有育哥无奔波2 天前
是采用示例模板,还是采用json的结构化数据,哪种方式会让llm的输出更加稳定?
json
小小李程序员2 天前
JSON.parse解析大整数踩坑
开发语言·javascript·json
西哥写代码4 天前
基于dcmtk的dicom工具 第九章 以json文件或sqlite为数据源的worklist服务(附工程源码)
sqlite·json·mfc·dcmtk·worklist
Mu.3874 天前
JSON解析
json
我今晚不熬夜4 天前
JSON在java中的使用
java·开发语言·json
妮妮喔妮5 天前
重构vite.config.json
javascript·重构·json
患得患失9495 天前
【前端】【vscode】【.vscode/settings.json】为单个项目配置自动格式化和开发环境
前端·vscode·json