RegExp.prototype.test()
test() 方法是 例項的一個方法,它使用該正則表示式來搜尋匹配項,以確定一個正則表示式是否與指定的字串匹配。如果匹配則返回 RegExptrue;否則返回 false。
當 JavaScript 物件設定了 RegExpglobal 或 sticky 標誌(例如 /foo/g 或 /foo/y)時,它們是有狀態的。它們會儲存上一次匹配的 lastIndex。test() 利用這一點,可以用來遍歷文字字串中的多個匹配項(包括捕獲組)。
試一試
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
語法
test(str)
引數
返回值
如果正則表示式與字串 str 匹配,則為 true。否則為 false。
描述
當您想知道字串中是否存在某個模式時,請使用 test()。test() 返回一個布林值,這與 String.prototype.search() 方法不同(該方法返回匹配項的索引,如果沒有找到則返回 -1)。
要獲取更多資訊(但執行速度較慢),請使用 exec() 方法。(這類似於 String.prototype.match() 方法。)
與 exec() 類似(或結合使用時),在同一個全域性正則表示式例項上多次呼叫 test() 會跳過之前的匹配項。
示例
使用 test()
此示例測試字串是否以 "hello" 開頭,並返回布林結果。
const str = "hello world!";
const result = /^hello/.test(str);
console.log(result); // true
以下示例會根據測試是否成功記錄一條訊息
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() 返回 true,lastIndex 就不會重置——即使測試的是不同的字串!
當 test() 返回 false 時,呼叫它的正則表示式的 lastIndex 屬性會重置為 0。
以下示例演示了這種行為
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 |
瀏覽器相容性
載入中…