RegExp.prototype.test()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

test() 方法是 RegExp 例項的一個方法,它使用該正則表示式來搜尋匹配項,以確定一個正則表示式是否與指定的字串匹配。如果匹配則返回 true;否則返回 false

當 JavaScript RegExp 物件設定了 globalsticky 標誌(例如 /foo/g/foo/y)時,它們是有狀態的。它們會儲存上一次匹配的 lastIndextest() 利用這一點,可以用來遍歷文字字串中的多個匹配項(包括捕獲組)。

試一試

const str = "table football";

const regex = /fo+/;
const globalRegex = /fo+/g;

console.log(regex.test(str));
// Expected output: true

console.log(globalRegex.lastIndex);
// Expected output: 0

console.log(globalRegex.test(str));
// Expected output: true

console.log(globalRegex.lastIndex);
// Expected output: 9

console.log(globalRegex.test(str));
// Expected output: false

語法

js
test(str)

引數

str

與正則表示式進行匹配的字串。所有值都會被強制轉換為字串,因此省略此引數或傳遞 undefined 會導致 test() 搜尋字串 "undefined",這通常不是您想要的。

返回值

如果正則表示式與字串 str 匹配,則為 true。否則為 false

描述

當您想知道字串中是否存在某個模式時,請使用 test()test() 返回一個布林值,這與 String.prototype.search() 方法不同(該方法返回匹配項的索引,如果沒有找到則返回 -1)。

要獲取更多資訊(但執行速度較慢),請使用 exec() 方法。(這類似於 String.prototype.match() 方法。)

exec() 類似(或結合使用時),在同一個全域性正則表示式例項上多次呼叫 test() 會跳過之前的匹配項。

示例

使用 test()

此示例測試字串是否以 "hello" 開頭,並返回布林結果。

js
const str = "hello world!";
const result = /^hello/.test(str);

console.log(result); // true

以下示例會根據測試是否成功記錄一條訊息

js
function testInput(re, str) {
  const midString = re.test(str) ? "contains" : "does not contain";
  console.log(`${str} ${midString} ${re.source}`);
}

在帶有“global”標誌的正則表示式上使用 test()

當正則表示式設定了 global 標誌時,test() 會推進正則表示式的 lastIndex 屬性。(RegExp.prototype.exec() 也會推進 lastIndex 屬性。)

後續對 test(str) 的呼叫將從 lastIndex 開始繼續搜尋 str。每次 test() 返回 true 時,lastIndex 屬性都會繼續增加。

注意: 只要 test() 返回 truelastIndex 就不會重置——即使測試的是不同的字串!

test() 返回 false 時,呼叫它的正則表示式的 lastIndex 屬性會重置為 0

以下示例演示了這種行為

js
const regex = /foo/g; // the "global" flag is set

// regex.lastIndex is at 0
regex.test("foo"); // true

// regex.lastIndex is now at 3
regex.test("foo"); // false

// regex.lastIndex is at 0
regex.test("barfoo"); // true

// regex.lastIndex is at 6
regex.test("foobar"); // false

// regex.lastIndex is at 0
regex.test("foobarfoo"); // true

// regex.lastIndex is at 3
regex.test("foobarfoo"); // true

// regex.lastIndex is at 9
regex.test("foobarfoo"); // false

// regex.lastIndex is at 0
// (...and so on)

規範

規範
ECMAScript® 2026 語言規範
# sec-regexp.prototype.test

瀏覽器相容性

另見