JavaScript's RegExp object is a vital tool for working with patterns in strings, enabling complex text manipulation, data validation, and extraction. Test methods like test() and exec() facilitate this interaction. Let's delve into these methods with practical examples.

RegExp test() and exec() methods play a significant role in pattern matching. Here's how to use them effectively:

Using test() for pattern matching
test() is a quick way to check if a patterns exists in a string. It returns a Boolean: true if found, false otherwise. Here's a simple example:

const str = "Hello, World!";
const pattern = /world/i;
console.log(pattern.test(str)); // Outputs: true
test() with flags

Test method accepts various flags (like i, g) to customize search behavior. The i flag ignores case, and g finds all matches instead of stopping at the first.
The code snippet below finds all comma-separated words:
/foo|bar/i.test('foo, bar, baz"); // Returns true, as 'foo' and 'bar' exist in the string.

Using exec() for pattern-finding and extraction
exec() returns an array of matches when found, and if no match exists. Unlike test, exec also captures groups and keeps track of the last index found.
Here's an example of using exec() with a group and capturing custom data:

const str = "My phone number is 123-456-7890";
const pattern = /phone(\d+)/i; // captures digits after 'phone'
console.log(pattern.exec(str)); // Outputs: [ 'phone123-456-7890', '123-456-7890' ].
exec() with all matches using the global flag




















Using g flag, exec() can find all matches in a string and return an array of all captured values. Each call to exec() returns the next match:
/foo/g.exec('foo, this, and foo too'); // Returns: [ 'foo' ]
In practice, the exec() method is helpful for string manipulation and data extraction, especially when you need to handle multiple matches and capture groups. Test these methods in your projects to harness the full potential of JavaScript's RegExp power.