Skip to content

Files

Latest commit

 

History

History
24 lines (18 loc) · 526 Bytes

prefer-regexp-test.md

File metadata and controls

24 lines (18 loc) · 526 Bytes

Pattern: String#match() or RegExp#exec() for boolean check

Issue: -

Description

When checking if a pattern exists in a string, RegExp#test() is more efficient than String#match() or RegExp#exec() as it only returns a boolean instead of creating a new array of matches.

Examples

Example of incorrect code:

if (string.match(/unicorn/)) {
}
if (/unicorn/.exec(string)) {
}

Example of correct code:

if (/unicorn/.test(string)) {
}
Boolean(string.match(/unicorn/));