JavaScript String includes()函数教程及示例

JavaScript提供 includes() 函数,以便在给定的字符串中搜索特定的子字符串。还有其他方法可以在字符串数组中搜索特定的字符串。

null

includes()函数语法

includes() 函数由字符串变量或字符串文本提供,以便在给定字符串中查找给定的搜索项。

STRING.icludes(SEARCH_TERM,START);
  • `STRING`是一个字符串变量或字符串文字,在这里搜索搜索项。
  • `includes()`是我们将用于以下参数的函数。此函数将根据情况和匹配返回布尔结果true和false。如果不匹配,则返回false,如果存在匹配,则返回true。
  • `SEARCHu TERM`是我们将在字符串中搜索的术语,可以是字符串变量或字符串文字。
  • `START`是搜索的起始索引号,从指定的起始索引开始字符串中的搜索。START是可选的,如果没有提供,搜索将从字符串的开头开始。

在整个字符串中搜索给定项

我们将从一个简单的例子开始,在这个例子中,我们将在给定的字符串中搜索一个简单的词。在本例中,我们将创建一个字符串变量 greeting 并使用includes()函数搜索greeting变量中的“poftut.com”。

var greeting="Hello my name is poftut.com. You can find very good tutorials about IT on me.";var match = greeting.includes("poftut.com");console.log(match);//Prints truevar match = "Hello my name is poftut.com. You can find very good tutorials about IT on me.".includes("poftut.com");console.log(match);//Prints truevar greeting="Hello my name is poftut.com. You can find very good tutorials about IT on me.";var match = greeting.includes("POFTUT.COM");console.log(match);//Prints false
Search Given Term In the Whole String
在整个字符串中搜索给定项

includes()是一个不区分大小写的函数,其中“poftut.com”和“poftut.com”不相同。所以它们在搜索中不匹配。

相关文章: JavaScript、java、python、C++、php、c、C++、PosiS壳编程语言中的字符串数据类型是什么?

在字符串的指定部分搜索给定项

includes() 函数还接受在索引之后执行搜索的搜索开始索引。在下面的示例中,我们将在第10个字符后搜索术语“poftut.com”。

var greeting="Hello my name is poftut.com. You can find very good tutorials about IT on me.";var match = greeting.includes("poftut.com",10);console.log(match);//Print to the console truevar match = greeting.includes("poftut.com",30);console.log(match);//Print to the console false
Search Given Term In the Specified Part Of The String
在字符串的指定部分搜索给定项

我们可以从示例中看到,当索引指定为10时,给定的字符串将匹配,includes()函数将返回true。如果我们将索引指定为30,它将不匹配并返回false。

比较includes()函数结果

As includes()函数返回布尔值true和false,我们可以将这些结果与JavaScript中与布尔逻辑相关的数字1和-1进行比较-1表示假,1表示真。

"Hello my name is poftut.com. You can find very good tutorials about IT on me.".includes("poftut.com");//Evaluated as true1 == "Hello my name is poftut.com. You can find very good tutorials about IT on me.".includes("poftut.com");//Evaluated as true1 == "Hello my name is poftut.com. You can find very good tutorials about IT on me.".includes("POFTUT.COM");//Evaluated as false-11 == "Hello my name is poftut.com. You can find very good tutorials about IT on me.".includes("POFTUT.COM");//Evaluated as false-1 == "Hello my name is poftut.com. You can find very good tutorials about IT on me.".includes("POFTUT.COM");//Evaluated as false
Comparing includes() Function Result
比较includes()函数结果

includes()可选索引Of()  功能

indexOf() 函数是 includes() 返回给定项的起始索引号的函数。如果不匹配,则返回-1。

var greeting="Hello my name is poftut.com. You can find very good tutorials about IT on me.";index=greeting.indexOf("poftut.com");console.log(index);//Output 17index=greeting.indexOf("POFTUT.COM");console.log(index);//Output -1
includes() Alternative indexOf()  Function
includes()可选索引Of()  功能
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享