一、基本介紹
在JavaScript中,indexOf函數是一種非常實用的字符串方法。這個方法可以用來查找一個字符串中是否包含另一個字符串,並返回被查找字符串的位置。
二、語法格式
string.indexOf(searchValue[, fromIndex])
其中,string代表要搜索的字符串,searchValue代表要查找的子字符串,fromIndex代表開始查找的位置,可選參數。
如果省略fromIndex,則默認從起始位置開始查找。如果fromIndex為負數,則表示倒數第n個字符開始查找。
三、用法舉例
1. 查找字符串中某個字符的位置
var str = "hello world";
var index = str.indexOf("o");
console.log(index);
// output: 4
以上代碼中,我們在字符串”hello world”中查找字符”o”的位置,返回的位置是4,即該字符在字符串中的第5個位置。
2. 查找字符串中的子字符串
var str = "hello world";
var subStr = "world";
var index = str.indexOf(subStr);
console.log(index);
// output: 6
以上代碼中,我們在字符串”hello world”中查找子字符串”world”的位置,返回的位置是6,即該子字符串在字符串中的第7個位置。
3. 從指定位置開始查找
var str = "hello world";
var subStr = "l";
var index = str.indexOf(subStr, 4);
console.log(index);
// output: 9
以上代碼中,我們在字符串”hello world”中查找字符”l”,並且指定從位置4開始查找,返回的位置是9,即該字符在字符串中的第10個位置。
4. 查找不存在的子字符串
var str = "hello world";
var subStr = "js";
var index = str.indexOf(subStr);
console.log(index);
// output: -1
以上代碼中,我們在字符串”hello world”中查找子字符串”js”,由於不存在該子字符串,所以返回-1。
5. 從字符串末尾開始查找
var str = "hello world";
var subStr = "o";
var index = str.lastIndexOf(subStr);
console.log(index);
// output: 7
以上代碼中,我們在字符串”hello world”中查找字符”o”,但是從字符串末尾開始查找,返回的位置是7,即該字符在字符串中的倒數第2個位置。
四、總結
indexOf函數在JavaScript中是一種非常常用的字符串方法,它可以快速查找字符串中是否包含某個子字符串,並返回被查找字符串的位置。除了indexOf函數外,還有lastIndexOf函數可以從字符串末尾開始查找子字符串。掌握這兩個函數的用法,可以使我們更加高效地處理字符串。
原創文章,作者:QMFCK,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/325181.html