indexOf返回索引,includes判断包含,startsWith检查开头。根据需求选择:需位置用indexOf,判断存在用includes,验证前缀用startsWith。

在 JavaScript 中处理字符串时,查找特定内容是常见需求。常用的字符串搜索方法有 indexOf、includes 和 startsWith。它们用途相似但返回值和使用场景略有不同,下面分别介绍。
indexOf 返回指定子字符串在原字符串中首次出现的索引位置。如果未找到,则返回 -1。
这个方法适合需要知道具体位置的场景。
const str = "Hello, welcome to JavaScript!";
立即学习“Java免费学习笔记(深入)”;
console.log(str.indexOf("welcome")); // 输出: 7
console.log(str.indexOf("Python")); // 输出: -1(未找到)
可以传入第二个参数指定开始搜索的位置:
console.log(str.indexOf("JavaScript", 10)); // 从索引10开始找
includes 返回布尔值,表示字符串是否包含指定内容。更直观,适合条件判断。
const message = "Today is a great day!";
console.log(message.includes("great")); // true
console.log(message.includes("bad")); // false
同样支持起始搜索位置:
console.log(message.includes("Today", 5)); // false,从第5个字符后找,“Today”不在后面
startsWith 判断字符串是否以指定内容开头,返回 true 或 false。常用于前缀匹配,比如验证协议或命令。
const url = "https://example.com";
console.log(url.startsWith("https")); // true
console.log(url.startsWith("http://")); // false
也可以指定从哪个位置开始判断:
console.log(url.startsWith("example", 8)); // true,从索引8开始是 "example.com"
基本上就这些。根据需求选择合适的方法:要位置用 indexOf,判断存在用 includes,检查开头用 startsWith。不复杂但容易忽略细节,比如大小写敏感和起始位置控制。实际使用时注意这些点即可。
以上就是JavaScript 字符串搜索:indexOf, includes 与 startsWith 的使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号