You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中指定索引位置使用str.includes()且不修改原字符串?

实现JavaScript中指定索引位置的子串检查

原生的String.prototype.includes()的第二个参数是起始搜索位置,而非精确匹配的起始索引——它只会从该位置开始往后查找是否存在目标子串,不会验证子串是否恰好从这个位置开始。比如如果字符串是"testtest",str.includes("test", 2)会返回true,因为从索引2开始能找到后面的"test",但实际上目标子串并不是从索引2开始的。

要实现精确检查指定索引位置是否匹配目标子串且不修改原字符串的功能,有两种简单的方法:

方法一:利用indexOf判断

indexOf会返回子串第一次出现的索引,我们只需要判断这个返回值是否等于指定的位置即可:

function includesAtPosition(str, searchStr, position) {
  // 如果不传position,默认从开头检查
  if (position === undefined) position = 0;
  return str.indexOf(searchStr, position) === position;
}

测试你的示例:

var str = "this is a test";
console.log(includesAtPosition(str, "test"));     // true(从0开始找,存在子串)
console.log(includesAtPosition(str, "test", 0));  // false(子串不是从0开始)
console.log(includesAtPosition(str, "test", 10)); // true(子串正好从10开始)

方法二:截取子串直接比较

通过slice截取指定位置开始、长度与目标子串一致的片段,再和目标子串对比:

function includesAtPosition(str, searchStr, position) {
  if (position === undefined) position = 0;
  // 先判断位置是否合法:不能小于0,且剩余长度要足够容纳目标子串
  if (position < 0 || position > str.length - searchStr.length) {
    return false;
  }
  return str.slice(position, position + searchStr.length) === searchStr;
}

两种方法都不会修改原字符串,因为indexOf和slice都是字符串的非破坏性方法,原字符串会保持原样。

内容的提问来源于stack exchange,提问作者Blue Herring

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:03:31