Skip to main content

JavaScript RegExp Methods (Live Playground)

In this tutorial, we'll explore some of the commonly used RegExp methods in JavaScript that allow us to search, match, and manipulate strings using regular expressions.

test()

The test() method checks whether a given string matches a regular expression pattern. It returns true if there's a match and false otherwise.

Example:

const regex = /hello/i;
const str1 = 'Hello, world!';
const str2 = 'Goodbye, world!';

console.log(regex.test(str1)); // true
console.log(regex.test(str2)); // false
Live Playground, Try it Yourself

exec()

The exec() method returns an array of information about the first match it finds in the given string. If there's no match, it returns null.

Example:

const regex = /(\d{2})\/(\d{2})\/(\d{4})/; // date pattern (MM/DD/YYYY)
const str = "Today's date is 12/31/2021.";

const result = regex.exec(str);

console.log(result);
// Output: ["12/31/2021", "12", "31", "2021", index: 16, input: "Today's date is 12/31/2021.", groups: undefined]

The returned array contains the matched string, capturing groups, and additional properties like index (position of the match) and input (input string).

Live Playground, Try it Yourself

Conclusion

In this tutorial, we covered some common RegExp methods in JavaScript, such as test(), exec(). These methods are essential for working with regular expressions, enabling us to search, match, and manipulate strings with ease.