JS中字符串的indexOf、startsWith、endsWith、includes

String.prototype.indexOf () 返回值完整说明

语法:str.indexOf(searchValue, [fromIndex])
作用:查找第一个匹配子串的起始下标,找不到返回 -1

  1. 返回 0
    子串出现在字符串最开头
    '/profile/1.jpg'.indexOf('/profile') // 0

  2. 返回大于 0 的数字(1、2、3…)
    子串出现在字符串中间 / 末尾,数字是匹配起始位置索引
    'https://xxx.com/profile/a.png'.indexOf('/profile') // 17

  3. 返回 -1
    字符串里完全不存在该子串
    'https://xxx.com/img/a.png'.indexOf('/profile') // -1


indexOf 返回值 vs startsWith /endsWith/includes

  1. xxx.indexOf(目标) === 0
    等价于:str.startsWith(目标)
    判断字符串以目标开头
let s = "/profile/1.jpg";
s.indexOf("/profile") === 0; // true
s.startsWith("/profile");    // true

let s2 = "https://a/profile";
s2.indexOf("/profile") === 0; // false
s2.startsWith("/profile");    // false
  1. xxx.indexOf(目标) > -1
    等价于:str.includes(目标)
    判断字符串包含目标任意位置
let s = "https://a/profile/1.jpg";
s.indexOf("/profile") > -1; // true
s.includes("/profile");     // true

let s2 = "/test/1.jpg";
s2.indexOf("/profile") > -1; // false
s2.includes("/profile");     // false
  1. xxx.indexOf(目标) === -1
    等价于:!str.includes(目标)
    判断字符串不包含目标
s.indexOf("/profile") === -1
// 等价
!s.includes("/profile")
  1. 额外补充:endsWith(无对应 indexOf 简洁写法)
    判断以某字符串结尾,indexOf 很难简洁实现,直接用 endsWith:
"test.jpg".endsWith(".jpg"); // true
posted @ 2026-07-17 14:28  yub4by  阅读(14)  评论(0)    收藏  举报