JavaScript 字串搜尋
字串搜尋方法
JavaScript String indexOf()
indexOf()
方法返回字串中 **第一個** 出現的子字串的 **索引**(位置),如果找不到該子字串,則返回 -1
注意
JavaScript 的位置計數從零開始。
0 是字串中的第一個位置,1 是第二個,2 是第三個,...
JavaScript String lastIndexOf()
lastIndexOf()
方法在字串中返回指定文字 **最後** 一次出現的 **索引**
示例
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");
自己動手試一試 »
如果找不到文字, indexOf()
和 lastIndexOf()
都會返回 -1
示例
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("John");
自己動手試一試 »
這兩個方法都接受第二個引數作為搜尋的起始位置
示例
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate", 15);
自己動手試一試 »
lastIndexOf()
方法向後搜尋(從末尾到開頭),這意味著:如果第二個引數是 15
,搜尋將從位置 15 開始,並搜尋到字串的開頭。
JavaScript String search()
search()
方法搜尋字串中的字串(或正則表示式),並返回匹配項的位置
示例
let text = "Please locate where 'locate' occurs!";
text.search("locate");
自己動手試一試 »
let text = "Please locate where 'locate' occurs!";
text.search(/locate/);
自己動手試一試 »
你注意到嗎?
這兩個方法, indexOf()
和 search()
,它們是 **相等** 的嗎?
它們接受相同的引數,並返回相同的值?
這兩個方法是 **不** 相等的。這些是區別
search()
方法不能接受第二個起始位置引數。indexOf()
方法不能接受強大的搜尋值(正則表示式)。
你將在後面的章節中瞭解更多關於正則表示式的知識。
JavaScript String match()
match()
方法返回一個數組,其中包含將字串與字串(或正則表示式)匹配的結果。
示例
搜尋 "ain"
let text = "The rain in SPAIN stays mainly in the plain";
text.match("ain");
自己動手試一試 »
搜尋 "ain"
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/);
自己動手試一試 »
執行全域性搜尋 "ain"
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/g);
自己動手試一試 »
執行全域性、不區分大小寫的搜尋 "ain"
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/gi);
自己動手試一試 »
JavaScript String matchAll()
matchAll()
方法返回一個迭代器,其中包含將字串與字串(或正則表示式)匹配的結果。
如果引數是正則表示式,則必須設定全域性標誌 (g),否則會丟擲 TypeError。
如果要進行不區分大小寫的搜尋,則必須設定不區分大小寫的標誌 (i)
JavaScript String includes()
includes()
方法如果字串包含指定值,則返回 true。
否則返回 false
。
示例
檢查字串是否包含 "world"
let text = "Hello world, welcome to the universe.";
text.includes("world");
自己動手試一試 »
檢查字串是否包含 "world"。從位置 12 開始
let text = "Hello world, welcome to the universe.";
text.includes("world", 12);
自己動手試一試 »
JavaScript String startsWith()
startsWith()
方法如果字串以指定值開頭,則返回 true
。
否則返回 false
示例
返回 true
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello");
自己動手試一試 »
返回 false
let text = "Hello world, welcome to the universe.";
text.startsWith("world")
自己動手試一試 »
可以指定搜尋的起始位置
返回 false
let text = "Hello world, welcome to the universe.";
text.startsWith("world", 5)
自己動手試一試 »
返回 true
let text = "Hello world, welcome to the universe.";
text.startsWith("world", 6)
自己動手試一試 »
JavaScript String endsWith()
endsWith()
方法如果字串以指定值結尾,則返回 true
。
否則返回 false
示例
檢查字串是否以 "Doe" 結尾
let text = "John Doe";
text.endsWith("Doe");
自己動手試一試 »
檢查字串的前 11 個字元是否以 "world" 結尾
let text = "Hello world, welcome to the universe.";
text.endsWith("world", 11);