JavaScript 字符串搜索
字符串搜索方法
JavaScript String indexOf()
indexOf()
方法返回字符串中 **第一个** 出现的子字符串的 **索引**(位置),如果找不到该子字符串,则返回 -1
注意
JavaScript 的位置计数从零开始。
0 是字符串中的第一个位置,1 是第二个,2 是第三个,...
JavaScript String lastIndexOf()
lastIndexOf()
方法在字符串中返回指定文本 **最后** 一次出现的 **索引**
示例
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");
自己动手试一试 »
如果找不到文本, indexOf()
和 lastIndexOf()
都会返回 -1
示例
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("John");
自己动手试一试 »
这两个方法都接受第二个参数作为搜索的起始位置
示例
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate", 15);
自己动手试一试 »
lastIndexOf()
方法向后搜索(从末尾到开头),这意味着:如果第二个参数是 15
,搜索将从位置 15 开始,并搜索到字符串的开头。
JavaScript String search()
search()
方法搜索字符串中的字符串(或正则表达式),并返回匹配项的位置
示例
let text = "Please locate where 'locate' occurs!";
text.search("locate");
自己动手试一试 »
let text = "Please locate where 'locate' occurs!";
text.search(/locate/);
自己动手试一试 »
你注意到吗?
这两个方法, indexOf()
和 search()
,它们是 **相等** 的吗?
它们接受相同的参数,并返回相同的值?
这两个方法是 **不** 相等的。这些是区别
search()
方法不能接受第二个起始位置参数。indexOf()
方法不能接受强大的搜索值(正则表达式)。
你将在后面的章节中了解更多关于正则表达式的知识。
JavaScript String match()
match()
方法返回一个数组,其中包含将字符串与字符串(或正则表达式)匹配的结果。
示例
搜索 "ain"
let text = "The rain in SPAIN stays mainly in the plain";
text.match("ain");
自己动手试一试 »
搜索 "ain"
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/);
自己动手试一试 »
执行全局搜索 "ain"
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/g);
自己动手试一试 »
执行全局、不区分大小写的搜索 "ain"
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/gi);
自己动手试一试 »
JavaScript String matchAll()
matchAll()
方法返回一个迭代器,其中包含将字符串与字符串(或正则表达式)匹配的结果。
如果参数是正则表达式,则必须设置全局标志 (g),否则会抛出 TypeError。
如果要进行不区分大小写的搜索,则必须设置不区分大小写的标志 (i)
JavaScript String includes()
includes()
方法如果字符串包含指定值,则返回 true。
否则返回 false
。
示例
检查字符串是否包含 "world"
let text = "Hello world, welcome to the universe.";
text.includes("world");
自己动手试一试 »
检查字符串是否包含 "world"。从位置 12 开始
let text = "Hello world, welcome to the universe.";
text.includes("world", 12);
自己动手试一试 »
JavaScript String startsWith()
startsWith()
方法如果字符串以指定值开头,则返回 true
。
否则返回 false
示例
返回 true
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello");
自己动手试一试 »
返回 false
let text = "Hello world, welcome to the universe.";
text.startsWith("world")
自己动手试一试 »
可以指定搜索的起始位置
返回 false
let text = "Hello world, welcome to the universe.";
text.startsWith("world", 5)
自己动手试一试 »
返回 true
let text = "Hello world, welcome to the universe.";
text.startsWith("world", 6)
自己动手试一试 »
JavaScript String endsWith()
endsWith()
方法如果字符串以指定值结尾,则返回 true
。
否则返回 false
示例
检查字符串是否以 "Doe" 结尾
let text = "John Doe";
text.endsWith("Doe");
自己动手试一试 »
检查字符串的前 11 个字符是否以 "world" 结尾
let text = "Hello world, welcome to the universe.";
text.endsWith("world", 11);