How to test and execute a regular expression in JavaScript?

JavaScript provides two main methods for testing and executing regular expressions: test() and exec(). The test() method returns a boolean indicating if a pattern matches, while exec() returns detailed match information or null.

Regular Expression Methods

There are two primary ways to work with regular expressions in JavaScript:

  • test() - Returns true/false if pattern matches
  • exec() - Returns match details or null

Example: Using test() and exec()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Regular Expression Testing</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        .result, .sample {
            font-size: 18px;
            font-weight: 500;
            margin: 10px 0;
        }
        .result {
            color: green;
        }
        .btn {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Testing and Executing Regular Expressions</h1>
    <div class="sample"></div>
    <div class="result"></div>
    <button class="btn">Test Regular Expression</button>
    <h3>Click the button to test and execute the regular expression</h3>
    
    <script>
        let sampleEle = document.querySelector('.sample');
        let resEle = document.querySelector('.result');
        let str = 'Hello world. This is a beautiful world';
        
        // Display the test string
        sampleEle.innerHTML = 'Test String: ' + str;
        
        // Create regular expression pattern
        let pattern = new RegExp("world", "g");
        
        document.querySelector(".btn").addEventListener("click", () => {
            // Clear previous results
            resEle.innerHTML = '';
            
            // Reset regex lastIndex for global flag
            pattern.lastIndex = 0;
            
            // Test method - returns boolean
            resEle.innerHTML += 'pattern.test(str) = ' + pattern.test(str) + '<br>';
            
            // Reset for exec method
            pattern.lastIndex = 0;
            
            // Exec method - returns match details
            let match = pattern.exec(str);
            resEle.innerHTML += 'pattern.exec(str) = ' + match + '<br>';
            resEle.innerHTML += 'Match found at index: ' + (match ? match.index : 'No match') + '<br>';
        });
    </script>
</body>
</html>

Understanding the Methods

test() Method

The test() method executes a search for a match between a regular expression and a string. It returns true if a match is found, false otherwise.

exec() Method

The exec() method executes a search for a match in a string. It returns an array with match information, or null if no match is found. The returned array contains:

  • The matched text as the first element
  • The index where the match was found
  • The original input string

Output

When you run the code and click the button, you'll see:

Test String: Hello world. This is a beautiful world
pattern.test(str) = true
pattern.exec(str) = world
Match found at index: 6

Key Differences

Method Return Type Use Case
test() Boolean Check if pattern exists
exec() Array or null Get match details and position

Conclusion

Use test() when you only need to verify if a pattern matches, and exec() when you need detailed information about the match, including its position and content.

Updated on: 2026-03-15T23:18:59+05:30

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements