JavaScript 字符串位置别混用:startsWith、endsWith 与 includes 实测

10-22 6阅读

同样传入第二个参数,startsWith、endsWith、includes 却不是在问同一个问题。写路径识别、文本协议检查或搜索框过滤时,最容易出错的不是方法名,而是把“起点”“终点”和“从此处继续找”混成一种位置。本文只讨论字符串,不把数组的 includes 规则搬过来。

JavaScript 字符串位置别混用:startsWith、endsWith 与 includes 实测
概念示意图:模型独立生成;字符带、方向与位置装饰均为示意,不代表精确索引、程序输出或真实界面。

一、先确定位置指向哪条边界

startsWith 要求搜索串恰好从指定位置开始;includes 则允许它出现在该位置或更后面。endsWith 的位置是匹配结束后的边界,不是最后一个字符的下标。可以先在脑中画出一个不含该位置的前缀,再问它是否以目标文本结尾;这是理解模型,不是在建议用切片重写标准方法。

下面处理一条带查询串的路径。问号下标为十五,因此检查问号之前的扩展名时,把十五作为结束边界。程序还故意把起点移过 report 的首字母,展示“允许往后找”不等于“允许回头找”。实际业务若可能没有问号,应先单独处理找不到分隔符的情况,不能直接把负一当作尾部位置。

const path = "docs/report.csv?download=1";
const end = path.indexOf("?");
if (end !== 15) throw new Error("query boundary");
function show(label, actual, expected) {
  if (actual !== expected) throw new Error(label);
  console.log(label + "=" + actual);
}
show("report-at-5", path.startsWith("report", 5), true);
show("csv-with-query", path.endsWith(".csv"), false);
show("csv-before-query", path.endsWith(".csv", end), true);
show("query-key", path.includes("download=", end + 1), true);
show("report-at-6", path.startsWith("report", 6), false);
show("report-after-6", path.includes("report", 6), false);

完整实际输出:

report-at-5=true
csv-with-query=false
csv-before-query=true
query-key=true
report-at-6=false
report-after-6=false

MDN 对起点匹配、结束边界与向后搜索分别说明了参数用途。读接口时,给第二参数取 start 或 end 这样的业务名字,比笼统叫 index 更不容易混淆。

二、默认值、取整和空串要一起看

省略位置和显式传 undefined,在这三个方法各自内部效果相同:startsWith、includes 从零开始,endsWith 使用字符串全长。但 null 和 NaN 不等于“省略”:它们作为位置会走数值转换,最终成为零。用位置或字符串长度的逻辑或表达式补默认值,会错误吞掉合法的零。

规范的 ToIntegerOrInfinity 先做数值转换,再向零截断有限小数,保留正负无穷;三个方法随后把位置限制在零到字符串长度之间。因此负数不是倒数索引,超大位置也不会越界抛错。数值字符串可以参与转换,但 BigInt、Symbol 位置可能触发 TypeError;不要把这种自动转换误认为业务输入已经通过校验。

空搜索串在有效边界上能匹配,包括截断到末尾的位置。不过,位置转换发生在返回空串匹配结果之前,所以不能推断“搜空串永远不会抛错”。搜索词若来自输入框,是否忽略空值应由业务明确决定,而不是靠 includes 自动过滤。

const text = "abcabc";
const rows = [
  ["undefined", undefined, [true, true, true]],
  ["null", null, [true, false, true]],
  ["NaN", NaN, [true, false, true]],
  ["-2", -2, [true, false, true]],
  ["1.9", 1.9, [false, false, true]],
  ["3.8-string", "3.8", [true, true, true]],
  ["Infinity", Infinity, [false, true, false]],
  ["-Infinity", -Infinity, [true, false, true]]
];
for (const [label, position, expected] of rows) {
  const actual = [text.startsWith("abc", position),
    text.endsWith("abc", position), text.includes("abc", position)];
  if (actual.some((value, i) => value !== expected[i])) {
    throw new Error(label);
  }
  console.log(label + ": " + actual.join(" "));
}
const empty = [text.startsWith("", Infinity),
  text.endsWith("", Infinity), text.includes("", Infinity)];
if (empty.some(value => value !== true)) throw new Error("empty");
console.log("empty-at-Infinity: " + empty.join(" "));
const unicode = "A\uD83D\uDE00B";
function show(label, actual, expected) {
  if (actual !== expected) throw new Error(label);
  console.log(label + "=" + actual);
}
show("code-unit-length", unicode.length, 4);
show("emoji-at-1", unicode.startsWith("\uD83D\uDE00", 1), true);
show("B-at-2", unicode.startsWith("B", 2), false);
show("B-at-3", unicode.startsWith("B", 3), true);
show("low-surrogate-at-2", unicode.startsWith("\uDE00", 2), true);

完整实际输出;前三列依次为 startsWith、endsWith、includes:

undefined: true true true
null: true false true
NaN: true false true
-2: true false true
1.9: false false true
3.8-string: true true true
Infinity: false true false
-Infinity: true false true
empty-at-Infinity: true true true
code-unit-length=4
emoji-at-1=true
B-at-2=false
B-at-3=true
low-surrogate-at-2=true

三、下标按码元计,不按视觉字符计

上例中的表情使用两个 UTF-16 码元,所以整串长度为四,B 在下标三而非二。下标二甚至能单独匹配低代理码元。这些方法不是按字形或用户眼中的字符分词,也不会自动进行 Unicode 规范化。若位置来自按码点或字素计算的界面选择,需要先统一计量单位,不能把数字直接混用。

同样要区分“位置省略”和“搜索词省略”:后者会转换成文本 undefined,而不是空串。数字接收者可借用这些方法并转换成字符串,null、undefined 接收者却会报错。这里讨论的是语言转换规则,不建议依赖意外类型完成输入清洗。

四、正则检查在字符串转换之前

三者拒绝被 IsRegExp 判定为正则的搜索值;这不只看对象是不是 RegExp 实例。该检查会读取 Symbol.match,已有且非 undefined 时按其布尔值决定。普通对象也可能被拒绝,正则显式设为 false 则可按文本转换后匹配;此时匹配的是斜线等字面内容,不是执行正则表达式。

下面给转换步骤加日志:先转换接收者,再读取 Symbol.match,再转换搜索词,最后转换位置。getter 或转换方法能够抛出异常,因此提前 String(search) 的封装不仅会放行本应拒绝的正则,还可能改变副作用发生顺序。

const methods = ["startsWith", "endsWith", "includes"];
for (const method of methods) {
  const trace = [];
  const receiver = {
    toString() { trace.push("receiver"); return "abc"; }
  };
  const search = {
    get [Symbol.match]() { trace.push("match"); return false; },
    toString() { trace.push("search"); return "b"; }
  };
  const position = {
    valueOf() { trace.push("position"); return method === "endsWith" ? 2 : 1; }
  };
  const result = String.prototype[method].call(receiver, search, position);
  const order = trace.join(">");
  if (result !== true || order !== "receiver>match>search>position") {
    throw new Error(method + " coercion order");
  }
  console.log(method + ": " + result + " " + order);
}
for (const method of methods) {
  let caught;
  try { "abc"[method](/b/); } catch (error) { caught = error; }
  if (!caught || caught.constructor !== TypeError) {
    throw new Error(method + " expected TypeError");
  }
  console.log(method + ": " + caught.name);
}
const literal = /b/;
literal[Symbol.match] = false;
const result = "/b/".includes(literal);
if (result !== true) throw new Error("literal regexp text");
console.log("regexp-as-text=" + result);

完整实际输出:

startsWith: true receiver>match>search>position
endsWith: true receiver>match>search>position
includes: true receiver>match>search>position
startsWith: TypeError
endsWith: TypeError
includes: TypeError
regexp-as-text=true

验证范围与使用建议

本文先人工冻结四十二个不同输入用例、八个错误封装见证及三个程序的完整预测输出,再编写和运行代码。Node.js v24.19.0 中,普通模式与带词法严格指令的 Function 执行体均通过;严格模式另用 this 为 undefined 的探针确认,所有执行均无标准错误输出,退出码为零,未修改人工预期。

正文三个程序可分别独立运行;完整边界用例和错误封装见证属于离线核验,不伪装成读者复制这三段便运行了全部测试。以上是本次实测和规范解释,不是浏览器全覆盖、性能比较或穷尽符合性证明。实践中先保证搜索词类型,再确认位置单位与边界方向,通常比自制“统一封装”可靠。

本次访问的规范算法:startsWith 算法、endsWith 算法、includes 算法、ToIntegerOrInfinity、IsRegExp、字符串码元与规范化规则。TC39 页面持续更新,引用其算法不表示本次 Node 版本实现了草案标示的全部语言特性。资料查阅及本地测试日期:北京时间二〇二六年十月二十二日。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。