To check if a string matches a regular expression (regex) in JavaScript, you can use the RegExp.test()
method or the String.match()
method. Below is a detailed guide with examples and best practices:
1. Using RegExp.test()
The test()
method returns true
if the regex matches the string, and false
otherwise.
Syntax:
const regex = /pattern/;
const result = regex.test(string);
Examples:
- Check if a string contains only letters:
const regex = /^[A-Za-z]+$/;
console.log(regex.test("Hello")); // true
console.log(regex.test("Hello123")); // false
- Case-insensitive match (using the
i
flag):
const regex = /hello/i; // 'i' flag ignores case
console.log(regex.test("HELLO")); // true
- Check for a date format (YYYY-MM-DD):
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
console.log(dateRegex.test("2023-10-05")); // true
console.log(dateRegex.test("05-10-2023")); // false
2. Using String.match()
The match()
method returns an array of matches or null
if no matches are found.
Syntax:
const matches = string.match(/pattern/);
const isMatch = matches !== null; // Convert to boolean
Examples:
- Check if a string contains a number:
const str = "Price: $200";
const hasNumber = str.match(/\d+/) !== null;
console.log(hasNumber); // true
- Extract all digits from a string:
const str = "Room 101, Floor 5";
const digits = str.match(/\d+/g); // 'g' flag for global search
console.log(digits); // ["101", "5"]
- Case-sensitive email validation:
const email = "user@example.com";
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test(email)); // true
3. Key Differences: test()
vs. match()
Aspect | RegExp.test() | String.match() |
---|---|---|
Return Value | true /false | Array of matches or null |
Use Case | Check if a pattern exists | Extract matched values |
Global Flag (g ) | Returns true once per match (stateful) | Returns all matches in an array |
Performance | Faster for simple checks | Slower (returns full match data) |
4. Common Regex Patterns
Validate a Phone Number:
const phoneRegex = /^(\+\d{1,3})?(\d{3}[-\s]?){2}\d{4}$/;
console.log(phoneRegex.test("123-456-7890")); // true
Check for a URL:
const urlRegex = /^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$/;
console.log(urlRegex.test("https://www.example.com")); // true
Password Strength Check:
// At least 8 chars, 1 uppercase, 1 number, 1 special character
const passwordRegex = /^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$/;
console.log(passwordRegex.test("Passw0rd!")); // true
5. Edge Cases & Best Practices
- Global Flag (
g
) Caveat:
test()
with theg
flag updates the regex object’slastIndex
property, leading to unexpected results in loops.- Example:
const regex = /a/g;
console.log(regex.test("abc")); // true
console.log(regex.test("abc")); // false (starts searching from index 1)
- Case Insensitivity:
Use thei
flag to ignore case:
const regex = /hello/i;
console.log(regex.test("HELLO")); // true
- Dynamic Regex Patterns:
Use theRegExp
constructor for dynamic patterns:
const pattern = "example";
const regex = new RegExp(pattern, "i"); // Case-insensitive
console.log(regex.test("EXAMPLE")); // true
- Special Characters:
Escape regex-specific characters like.
,*
, and+
with a backslash (\
):
const regex = /\.jpg$/; // Matches filenames ending with ".jpg"
console.log(regex.test("image.jpg")); // true
Summary
- Use
RegExp.test()
for simple existence checks (returnstrue
/false
). - Use
String.match()
to extract matched substrings. - Always test your regex patterns thoroughly (e.g., RegExr).