在 TypeScript 中,可以使用 indexOf 函数来查找字符串中某个子字符串第一次出现的位置。假设有一个 JSON 字符串如下:

const jsonString = `{"name": "John", "age": 25, "city": "New York"}`;

要使用 indexOf 函数查找子字符串在 JSON 字符串中的位置,可以按照以下步骤进行:

  1. 将 JSON 字符串转换为 JavaScript 对象或数组,可以使用 JSON.parse 函数将其解析为对象或数组:
const json = JSON.parse(jsonString);
  1. 将 JSON 对象或数组转换为字符串,可以使用 JSON.stringify 函数:
const jsonString = JSON.stringify(json);
  1. 使用 indexOf 函数查找子字符串在 JSON 字符串中的位置,例如查找字符串 "age"
const index = jsonString.indexOf("age");
console.log(index); // 输出: 14

请注意,indexOf 函数返回第一次出现的索引位置,如果子字符串不存在,则返回 -1


原文地址: https://www.cveoy.top/t/topic/iZAG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录