includes() 方法是一种搜索算法,用于查找字符串中的子串或查找数组中的元素。includes() 方法返回布尔值(它返回真或假)。因此,它可以被用作if语句或循环的条件。
在本指南中,我们将学习如何使用includes() 方法来查找字符串中的子串;但首先,让我们讨论JavaScript中includes() 的语法。
语法。
string_name.includes(substring, starting_point)
array_name.includes(element, starting_point)
在JavaScript中include()方法需要两个参数。
- substring/element。第一个参数是必须的。它是需要在字符串/数组中找到的子串/元素。
- starting_point:这个参数是可选的。它给出了开始搜索的位置。默认情况下是0 。
includes()和contains()的区别
includes和contains 都是搜索算法,用于查找字符串中的子串或查找数组中的元素。includes() 是JavaScript原生的方法,而contains() 则是在其他语言中使用,比如Java。所以从现在开始,我们在文章中只使用includes()。
注意:我们将使用浏览器控制台来演示本篇文章中执行的例子。要打开浏览器的控制台。
- 在Chrome和其他基于chromium的浏览器中使用F12键。
- 在Mozilla使用CTRL + SHIFT + K键盘快捷键。
- 在Safari浏览器中使用Option + ⌘ + C键盘快捷键(如果没有出现开发者菜单,请按⌘ + ,打开偏好,在高级标签中勾选 "在菜单栏中显示开发菜单")。
如何在一个字符串中找到一个子串(JavaScript
现在我们将使用includes()方法来查找字符串中的子串。
var str = 'Welcome to Linux Hint!';
if(str.includes('to Linux'))
{
console.log('Success');
}
在上面的例子中,我们首先声明了一个字符串;然后我们给它分配了一个值。在下一行,我们使用includes() 方法作为if语句的一个条件,并将一个字符串作为参数传给它。由于该字符串存在于名为str的原始字符串中,includes() 方法将返回true,并且if 语句的主体将被执行。如果includes方法没有在原始字符串中找到该子串,那么条件将变为false, if语句的主体将不会被执行。
我们还可以将变量作为参数传递给includes() 方法。
var str = 'Welcome to Linux Hint!';
let find = 'Linux';
if(str.includes(find))
{
console.log(`The string does contain "${find}"`);
}
includes() 方法是区分大小写的。
var str = 'THIS STRING IS WRITTEN IN UPPER CASE';
if(str.includes('this string is written'))
{
console.log('The required string found');
}
else
{
console.log('Could not find the required string');
}
我们还可以向includes() 方法传递另一个参数,指定它将在哪里开始搜索。
var str = 'THIS STRING IS WRITTEN IN UPPER CASE';
if(str.includes('STRING', 5))
{
console.log('The required string found');
}
else
{
console.log('Could not find the required string');
}
var str = 'THIS STRING IS WRITTEN IN UPPER CASE';
if(str.includes('STRING', 6))
{
console.log('The required string found');
}
else
{
console.log('Could not find the required string');
}
同样,这个方法也可以用来寻找数组中的一个元素。
vararr = ['Lion', 'Monkey', 'Rhino', 'Dog', 'Cat'];
if(arr.includes('Monkey'))
{
console.log('The required element found');
}
else
{
console.log('Could not find the required element');
}
结论
在编程语言中处理数组或字符串时,你经常需要找到它们是否包含一个特定的元素或一个子串。includes()方法可以帮助我们解决这个问题。
在本指南中,我们已经学会了如何使用 includes()方法来查找字符串/数组中的子串/元素。此外,我们还讨论了我们可以传递给includes() 方法的类型和参数。