使用 JavaScript 的 indexOf() 和 lastIndexOf() 查找字符串位置
创建时间 2026-12-02
最后修改 2026-12-02
indexOf() 返回 JavaScript 字符串中第一个匹配的起始索引,lastIndexOf() 返回最后一个。索引从零开始。两者区分大小写,找不到时返回 -1。
查找首个和最后一个匹配
const text = 'banana';
console.log(text.indexOf('ana')); // 1
console.log(text.lastIndexOf('ana')); // 3
console.log(text.indexOf('ANA')); // -1
console.log(text.indexOf('b')); // 0
请将结果与 -1 比较。直接放进条件中,匹配位置 0 会被视为假,而未找到的 -1 会被视为真。只需判断是否包含时,可用 includes()。请参阅 indexOf() 和 lastIndexOf()。
为两个查找方向指定位置
第二个参数限制匹配的起始位置。indexOf() 取最早允许的位置,lastIndexOf() 取最晚允许的位置。匹配可以从指定位置开始,向后查找时也可能在该位置之后结束。
| 表达式 | 结果 | 原因 |
|---|---|---|
"banana".indexOf("ana", 2) |
3 |
下一匹配从 2 或之后开始 |
"banana".lastIndexOf("ana", 2) |
1 |
最后一个匹配在 2 或之前开始 |
"banana".indexOf("z") |
-1 |
没有匹配 |
首次查找成功后,从 first + 1 开始可以找到重叠的匹配,从 first + query.length 开始则会跳过重叠部分。首次返回 -1 时停止。
const first = 'banana'.indexOf('ana'); // 1
const overlapping = 'banana'.indexOf('ana', first + 1); // 3
const nonOverlapping = 'banana'.indexOf('ana', first + 'ana'.length); // -1
运行完整的查找示例
将完整代码以 UTF-8 保存为 search-example.html 并打开。初始结果为 1 和 3,位置填 2 后为 3 和 1。查找 ANA 时两者都返回 -1。空查询或无效位置会显示提示。重置可恢复初始字段。
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>比较字符串查找位置</title>
</head>
<body>
<label for="text">原始字符串</label>
<input id="text" type="text" value="banana">
<label for="query">要查找的内容</label>
<input id="query" type="text" value="ana">
<label for="position">起始位置(留空使用默认值)</label>
<input id="position" type="text" inputmode="numeric">
<button id="search" type="button">查找</button>
<button id="reset" type="button">重置</button>
<pre id="output" aria-live="polite"></pre>
<script>
const textInput = document.querySelector('#text');
const queryInput = document.querySelector('#query');
const positionInput = document.querySelector('#position');
const output = document.querySelector('#output');
function search() {
const text = textInput.value;
const query = queryInput.value;
const rawPosition = positionInput.value.trim();
if (query === '') {
output.textContent = '请输入要查找的内容。';
return;
}
if (rawPosition !== '' && !/^(0|[1-9]\d*)$/.test(rawPosition)) {
output.textContent = '起始位置必须是大于或等于 0 的整数。';
return;
}
const position = rawPosition === '' ? null : Number(rawPosition);
if (position !== null && !Number.isSafeInteger(position)) {
output.textContent = '请输入安全整数范围内的位置。';
return;
}
const first = position === null
? text.indexOf(query)
: text.indexOf(query, position);
const last = position === null
? text.lastIndexOf(query)
: text.lastIndexOf(query, position);
output.textContent = `indexOf: ${first}\nlastIndexOf: ${last}`;
}
document.querySelector('#search').addEventListener('click', search);
document.querySelector('#reset').addEventListener('click', () => {
textInput.value = 'banana';
queryInput.value = 'ana';
positionInput.value = '';
search();
});
search();
</script>
</body>
</html>
检查空查询和 UTF-16 索引
方法本身支持空查询,而本演示会拒绝。省略位置时分别返回零和字符串长度。显式输入整数时,返回限制在字符串范围内的位置。
索引按 UTF-16(16 位 Unicode 转换格式)代码单元计算。第一个表情符号占两个单元,所以 a 虽然是第二个可见字符,起始索引却是 2。不要直接用这个索引表示可见字符的数量。
{
const letters = 'abc';
console.log(letters.indexOf('')); // 0
console.log(letters.lastIndexOf('')); // 3
console.log(letters.indexOf('', 99)); // 3
console.log(letters.lastIndexOf('', 1)); // 1
const text = '😀a😀';
console.log(text.indexOf('a')); // 2
console.log(text.lastIndexOf('😀')); // 3
console.log(text.length); // 5
}




