JavaScript String – indexOf() 方法
在JavaScript字符串中,indexOf()方法用于查找字符串中給定子字符串的第一個(gè)匹配項(xiàng)的位置。愛(ài)掏網(wǎng) - it200.com它可以接收兩個(gè)參數(shù),第一個(gè)參數(shù)是要搜索的字符串,第二個(gè)參數(shù)是要搜索的目標(biāo)字符串。愛(ài)掏網(wǎng) - it200.com如果找到目標(biāo)字符串,則返回第一個(gè)匹配項(xiàng)的索引,否則返回-1。愛(ài)掏網(wǎng) - it200.com
string.indexOf(searchValue[, fromIndex])
參數(shù)
searchValue
:要搜索的字符串。愛(ài)掏網(wǎng) - it200.comfromIndex
:從哪個(gè)位置開(kāi)始搜索。愛(ài)掏網(wǎng) - it200.com如果不傳該參數(shù),則默認(rèn)從字符串的第一個(gè)字符開(kāi)始搜索。愛(ài)掏網(wǎng) - it200.com如果該參數(shù)小于0,則從字符串末尾開(kāi)始計(jì)算索引。愛(ài)掏網(wǎng) - it200.com如果該參數(shù)大于或等于字符串長(zhǎng)度,則永遠(yuǎn)不會(huì)找到匹配項(xiàng),返回-1。愛(ài)掏網(wǎng) - it200.com
返回值
返回搜索到的第一個(gè)匹配項(xiàng)的索引。愛(ài)掏網(wǎng) - it200.com如果沒(méi)有找到,則返回-1。愛(ài)掏網(wǎng) - it200.com
示例
接下來(lái),我們將用一些示例來(lái)說(shuō)明如何使用JavaScript字符串的indexOf()方法。愛(ài)掏網(wǎng) - it200.com
在字符串中搜索一個(gè)單詞
我們來(lái)看一個(gè)簡(jiǎn)單的例子,如何使用indexOf()方法在一個(gè)字符串中搜索一個(gè)單詞:
var str = "Hello world, welcome to JavaScript";
var index = str.indexOf("welcome");
if (index !== -1) {
console.log("Found the word at index ", index);
} else {
console.log("The word was not found");
}
輸出結(jié)果:
Found the word at index 13
在這個(gè)例子中,我們首先定義了一個(gè)字符串str
,然后調(diào)用了indexOf()方法,將待搜索的單詞”welcome”作為方法的參數(shù)傳入。愛(ài)掏網(wǎng) - it200.com由于這個(gè)單詞位于字符串的第13個(gè)位置,因此我們得到的結(jié)果是”Found the word at index 13″。愛(ài)掏網(wǎng) - it200.com
搜索所有匹配項(xiàng)
除了搜索第一個(gè)匹配項(xiàng)之外,我們還可以使用循環(huán)來(lái)搜索字符串中的所有匹配項(xiàng)。愛(ài)掏網(wǎng) - it200.com下面的示例演示了如何使用indexOf()方法搜索字符串中的所有匹配項(xiàng):
var str = "The quick brown fox jumps over the lazy dog";
var searchStr = "o";
var index = 0;
while (index !== -1) {
index = str.indexOf(searchStr, index);
if (index !== -1) {
console.log("Found at index ", index);
index++;
}
}
輸出結(jié)果:
Found at index 20
Found at index 25
Found at index 27
Found at index 31
Found at index 35
Found at index 39
Found at index 42
Found at index 45
在此示例中,我們定義了一個(gè)字符串str
和要搜索的子字符串searchStr
。愛(ài)掏網(wǎng) - it200.com然后我們使用while循環(huán)和indexOf()方法來(lái)搜索字符串中所有匹配項(xiàng)。愛(ài)掏網(wǎng) - it200.com注意,當(dāng)找到一個(gè)匹配項(xiàng)后,我們將下一次從該匹配項(xiàng)的下一個(gè)字符開(kāi)始搜索,這是為了避免重復(fù)搜索同一個(gè)匹配項(xiàng)。愛(ài)掏網(wǎng) - it200.com
從字符串的末尾開(kāi)始搜索
如果從字符串的末尾開(kāi)始,我們可以使用負(fù)數(shù)的fromIndex值來(lái)實(shí)現(xiàn)。愛(ài)掏網(wǎng) - it200.com下面是一個(gè)例子:
var str = "The quick brown fox jumps over the lazy dog";
var searchStr = "o";
var index = str.indexOf(searchStr, -1);
console.log("The last occurrence of " + searchStr + " is at index ", index);
輸出結(jié)果:
The last occurrence of o is at index 45
在此示例中,我們使用負(fù)數(shù)-1作為fromIndex參數(shù)來(lái)指定從字符串的末尾開(kāi)始搜索。愛(ài)掏網(wǎng) - it200.com由于字符串中最后一個(gè)o的索引為45,因此我們得到的結(jié)果是”The last occurrence of o is at index 45″。愛(ài)掏網(wǎng) - it200.com
結(jié)論
JavaScript字符串的indexOf()方法是一個(gè)常用的方法,用于在字符串中查找一個(gè)特定的子字符串。愛(ài)掏網(wǎng) - it200.com我們可以使用它來(lái)搜索字符串中的所有匹配項(xiàng),或者指定從字符串的末尾開(kāi)始搜索。愛(ài)掏網(wǎng) - it200.com希望這篇文章能夠幫助你更好地理解和應(yīng)用JavaScript字符串的indexOf()方法。愛(ài)掏網(wǎng) - it200.com