How to check whether a string matches a regex in JS ?

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:

  1. Check if a string contains only letters:
   const regex = /^[A-Za-z]+$/;
   console.log(regex.test("Hello"));   // true
   console.log(regex.test("Hello123")); // false
  1. Case-insensitive match (using the i flag):
   const regex = /hello/i; // 'i' flag ignores case
   console.log(regex.test("HELLO")); // true
  1. 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:

  1. Check if a string contains a number:
   const str = "Price: $200";
   const hasNumber = str.match(/\d+/) !== null;
   console.log(hasNumber); // true
  1. 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"]
  1. 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()

AspectRegExp.test()String.match()
Return Valuetrue/falseArray of matches or null
Use CaseCheck if a pattern existsExtract matched values
Global Flag (g)Returns true once per match (stateful)Returns all matches in an array
PerformanceFaster for simple checksSlower (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

  1. Global Flag (g) Caveat:
  • test() with the g flag updates the regex object’s lastIndex 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)
  1. Case Insensitivity:
    Use the i flag to ignore case:
   const regex = /hello/i;
   console.log(regex.test("HELLO")); // true
  1. Dynamic Regex Patterns:
    Use the RegExp constructor for dynamic patterns:
   const pattern = "example";
   const regex = new RegExp(pattern, "i"); // Case-insensitive
   console.log(regex.test("EXAMPLE")); // true
  1. 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 (returns true/false).
  • Use String.match() to extract matched substrings.
  • Always test your regex patterns thoroughly (e.g., RegExr).

Leave a Reply

Your email address will not be published. Required fields are marked *