在JavaScript中,如果需要查找一個字元串的最後一次出現的位置,可以使用lastIndexOf()方法。該方法返回指定字元串最後出現的位置。如果沒找到該字元串,則返回-1。
一、lastIndexOf()方法的基本使用
lastIndexOf()方法可以接受兩個參數,第一個參數是要查找的字元串,第二個參數是可選的,表示從哪個位置開始查找。如果未傳入第二個參數,則默認從字元串的末尾開始查找。
const str = "hello world";
const lastIndex = str.lastIndexOf("o");
console.log(lastIndex); // 7
上面的代碼中,lastIndexOf()方法查找字元串中最後一次出現字母o的位置,並返回7。
二、lastIndexOf()方法查找多次出現的字元串
如果要查找一個字元串中多次出現的某個字元串最後一次出現的位置,可以通過循環使用lastIndexOf()方法來實現。
const str = "hello world";
let lastIndex = str.lastIndexOf("o");
while(lastIndex !== -1) {
console.log(lastIndex);
lastIndex = str.lastIndexOf("o", lastIndex - 1);
}
上面的代碼中,while循環通過lastIndexOf()方法查找字元串中所有字母o的位置,並依次輸出。
三、lastIndexOf()方法的使用場景
lastIndexOf()方法可用於以下場景:
1、判斷字元串中是否含有某個子串
const str = "hello world";
const hasSubstr = str.lastIndexOf("o") !== -1;
console.log(hasSubstr); // true
上面的代碼中,判斷字元串中是否含有字母o。
2、查找某個字元在字元串中最後一次出現的位置
const str = "/usr/local/bin/node";
const lastIndex = str.lastIndexOf("/");
const filename = str.substring(lastIndex + 1);
console.log(filename); // node
上面的代碼中,查找字元串中最後一個反斜杠的位置,並從該位置分割字元串,獲取文件名。
3、反轉字元串
const str = "hello world";
let reversedStr = "";
let lastIndex = str.length - 1;
while(lastIndex >= 0) {
reversedStr += str[lastIndex];
lastIndex--;
}
console.log(reversedStr); // dlrow olleh
上面的代碼中,循環使用lastIndexOf()方法,依次將字元串反轉。
四、總結
lastIndexOf()方法是JavaScript中用於查找字元串最後一次出現位置的方法。使用該方法可以實現許多字元串操作,如反轉字元串等。在使用該方法時,需要注意該方法返回的是索引值,若找不到對應的字元串則返回-1。
原創文章,作者:ARIU,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/150026.html
微信掃一掃
支付寶掃一掃