JavaScript中搜索子字符串的方法包括:indexOf()返回首次出现的索引,lastIndexOf()返回最后一次出现的索引,includes()判断是否包含子串并返回布尔值,search()支持正则表达式匹配并返回第一个匹配位置,matchAll()则通过全局正则获取所有匹配项及其位置信息。

JavaScript 中提供了多种方法来搜索字符串中某个子字符串的位置。这些方法能帮助你快速定位字符或子串在原字符串中的索引位置,适用于文本处理、表单验证等场景。
indexOf() 方法用于查找指定子字符串在原字符串中第一次出现的索引。如果找到,返回对应的索引值;否则返回 -1。
说明:示例:
const str = "hello world";
console.log(str.indexOf("l")); // 2
console.log(str.indexOf("world")); // 6
console.log(str.indexOf("x")); // -1(未找到)
console.log(str.indexOf("l", 3)); // 3(从索引3开始找)
lastIndexOf() 方法查找指定子字符串在原字符串中最后一次出现的索引,也是从右往左搜索,但仍返回从左数的索引位置。
说明:示例:
const str = "hello world";
console.log(str.lastIndexOf("l")); // 9
console.log(str.lastIndexOf("o")); // 7
console.log(str.lastIndexOf("l", 8)); // 3(从索引8之前找最后一个"l")
虽然 includes() 不返回具体位置,但它常用于判断是否存在某个子串,返回布尔值。
说明:示例:
const str = "hello world";
console.log(str.includes("world")); // true
console.log(str.includes("bye")); // false
console.log(str.includes("lo", 4)); // true(从索引4开始是否包含"lo")
search() 方法使用正则表达式进行匹配,返回第一个匹配项的索引,未找到则返回 -1。
说明:示例:
const str = "Hello World"; console.log(str.search(/world/i)); // 6(i 表示忽略大小写) console.log(str.search(/xyz/)); // -1
如果你需要更详细的信息,比如每个匹配项的位置和内容,可以使用 matchAll(),它返回一个迭代器,每个结果都包含匹配文本和 index 属性(即位置)。
match() 只返回匹配内容,不便于获取位置。matchAll() 配合全局正则使用,能拿到所有匹配的位置。示例:
const str = "abc abc abc";
const regex = /abc/g;
for (const match of str.matchAll(regex)) {
console.log(`找到 "${match[0]}" 在位置 ${match.index}`);
}
// 输出:
// 找到 "abc" 在位置 0
// 找到 "abc" 在位置 4
// 找到 "abc" 在位置 8
以上就是js中字符串位置的搜索方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号