本人github
在JavaScript中,有多种方法可以用来检查一个字符串是否包含另一个字符串:
1. String.prototype.includes()
这个方法返回一个布尔值,表示一个字符串是否包含另一个字符串。
const str = "Hello, world!";
const result = str.includes("world"); // 返回 true
2. String.prototype.indexOf()
这个方法返回一个整数,表示子字符串在字符串中首次出现的索引位置,或者如果没有找到则返回-1。
const str = "Hello, world!";
const result = str.indexOf("world"); // 返回 7
3. String.prototype.search()
这个方法执行一个正则表达式搜索,并返回一个整数,表示匹配项在字符串中的位置,或者如果没有找到则返回-1。
const str = "Hello, world!";
const result = str.search("world"); // 返回 7
4. 正则表达式
你也可以使用正则表达式的test()
方法来检查一个字符串是否包含另一个字符串。
const str = "Hello, world!";
const regex = /world/;
const result = regex.test(str); // 返回 true
这些方法各有其用途和局限性,你可以根据具体需求选择最适合你的方法。