JavaScript String search() 方法
示例
搜尋 "Blue"
let text = "Mr. Blue has a blue house";
let position = text.search("Blue");
自己動手試一試 »
搜尋 "blue"
let text = "Mr. Blue has a blue house";
let position = text.search("blue");
自己動手試一試 »
搜尋 /Blue/
let text = "Mr. Blue has a blue house";
let position = text.search(/Blue/);
自己動手試一試 »
搜尋 /blue/
let text = "Mr. Blue has a blue house";
let position = text.search(/blue/);
自己動手試一試 »
不區分大小寫搜尋
let text = "Mr. Blue has a blue house";
let position = text.search(/blue/i);
自己動手試一試 »
描述
search()
方法將字串與正則表示式進行匹配**
search()
方法返回第一個匹配的索引(位置)。
search()
方法在未找到匹配項時返回 -1。
search()
方法區分大小寫。
語法
string.search(searchValue)
引數
引數 | 描述 |
searchValue | 必需。 搜尋值。 正則表示式(或將轉換為正則表示式的字串)。 |
返回值
型別 | 描述 |
一個數字 | 第一個匹配的位置。 如果沒有匹配項,則為 -1。 |
區別
String search() 和 String indexOf()
search()
不能接受起始位置引數。
indexOf()
方法不能針對正則表示式進行搜尋。
區別
String search() 和 String match()
search()
方法返回第一個匹配的位置。
match()
方法返回一個匹配項陣列。
正則表示式搜尋方法
在 JavaScript 中,可以使用不同的方法進行正則表示式文字搜尋。
以模式作為正則表示式,這些是最常用的方法
示例 | 描述 |
---|---|
text.match(pattern) | 字串方法 match() |
text.search(pattern) | 字串方法 search() |
pattern.exec(text) | RegExp 方法 exec() |
pattern.test(text) | RegExp 方法 test() |
瀏覽器支援
search()
是 ECMAScript1 (ES1) 的特性。
ES1 (JavaScript 1997) 在所有瀏覽器中都得到完全支援
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 是 |