当前位置: 首页 > article >正文

解锁 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 的强大能力。试试这些方法,优化你的数据处理吧!


在这里插入图片描述


http://www.kler.cn/a/567264.html

相关文章:

  • 梯度下降法(Gradient Descent) -- 现代机器学习的血液
  • 【项目管理】基于 C 语言的 QQ 聊天室实现(TCP + 多线程 + SQLite3)后续部分代码优化
  • readline模块详解!!【Node.js】
  • Github 2025-03-01 开源项目月报 Top19
  • Ubuntu 下 nginx-1.24.0 源码分析 - ngx_conf_add_dump
  • 分布式数据存储:提升系统弹性与性能的技术之路
  • 使用vLLM部署DeepSeek-R1-Distill-Qwen-7B模型:从环境配置到高效推理
  • 在 SQLite 中使用 SpatiaLite 实现地理空间数据自动化读写
  • 考虑复杂遭遇场景下的COLREG,基于模型预测人工势场的船舶运动规划方法附Matlab代码
  • 【NLP面试八股-NLP常见面试问题详细回答】
  • 前端关于Cursor编辑器的了解与深度使用及对工作的便利
  • Spring Boot3+Vue3极速整合: 10分钟搭建DeepSeek AI对话系统(进阶)
  • MySQL锁分类
  • Oracle Enterprise Manager (OEM)安装部署
  • LeetCode热题100JS(20/100)第四天|​41. 缺失的第一个正数​|​73. 矩阵置零​|​54. 螺旋矩阵​|​48. 旋转图像​
  • Flutter 学习之旅 之 flutter 在 Android 端进行简单的打开前后相机预览 / 拍照保存
  • 【星云 Orbit-F4 开发板】05. NVIC中断分组与配置(重要)
  • 最新!!!DeepSeek开源周发布内容汇总
  • 小程序性能优化-预加载
  • 【网络安全】敏感字段扫描工具(可用于漏洞挖掘、代码审计)