JavaScript 哪个方法返回调用字符串对象中指定值的第一个出现的索引
在这篇文章中,我们将了解如何返回字符串中指定值(可以是字符串或字符)的第一个出现的索引,同时通过示例了解它们的实现。
JavaScript indexOf() 方法: indexOf() 方法是一个内置的且区分大小写的方法,它返回调用字符串对象中指定值的第一个出现的索引。如果找不到这样的值,它将返回-1。
这种方法的主要用途是查找字符串中特定字符串或字符的存在,因为如果提供的搜索值不存在,该方法会返回-1。此方法还可以用于计算字符串中特定搜索值的频率。
语法:
indexOf(searchValue, index)
示例1: 此示例说明了可以是字符串或任何字符的搜索值。
Javascript
let myString = "Hello, GeeksforGeeks Learner!";
console.log("The index of 'Hello' in string is: ",
myString.indexOf("Hello"));
console.log("The index of first occurrence of 'G' is: ",
myString.indexOf('G'));
输出:
The index of 'Hello' in string is: 0
The index of first occurrence of 'G' is: 7
解释: 在第一行,我们声明了一个带有初始化的字符串,然后我们通过将“Hello”作为参数,使用该字符串作为调用对象调用了indexOf()方法。现在,该方法将返回字符串中“Hello”的第一次出现,即0。然后,我们在字符串中搜索字符‘G’。在这里,该方法将返回7,因为那是第一次出现的位置。
示例2: 该示例描述了相对于特定位置的参数字符或字符串的第一次出现的查找。
HTML
let myString = "Hi Javascript Developer";
console.log("The index of first occurrence 'i' from 3rd index is: ",
myString.indexOf("i", 3));
console.log("The index of first occurrence 'Hi' from the 7th index is: ",
myString.indexOf('Hi', 7));
输出:
The index of first occurrence 'i' from 3rd index is: 10
The index of first occurrence 'Hi' from the 7th index is: -1
说明: 在这里,我们通过显式提供搜索起始索引来调用indexOf() 方法。在第一个示例中,我们通过提供’i’和3来调用该方法。如果起始搜索索引是3,那么’i’将在第10个索引处找到。同样,在第二个示例中,我们提供了’Hi’来从第7个索引开始搜索,但在第7个索引后没有出现“Hi”,因此将返回-1。