RegExp methods in JavaScript are used to test patterns, find matches, extract data, and work with strings using regular expressions. JavaScript provides methods on the RegExp object and also supports RegExp usage through string methods. These methods help in validation, searching, replacing, and splitting text.

RegExp Object Methods

test()

Checks whether a pattern matches a string and returns true or false.

Explanation:

Returns true because the pattern cat exists in the string (case-insensitive).

exec()

Finds a match and returns details about the first match.

Explanation:

Returns the first number found along with its position in the string.

String Methods That Use RegExp

match()

Returns matches of a pattern from a string.

Explanation:

Returns all occurrences of red as an array.

search()

Returns the index of the first match or -1 if not found.

Explanation:

Returns the starting index of JavaScript.

replace()

Replaces matched text with new text.

Explanation:

Replaces apples with oranges.

split()

Splits a string using a pattern.

Explanation:

Splits the string at commas and optional spaces.

When to Use Which Method

TaskMethod
Check if match existstest()
Get match detailsexec()
Get all matchesmatch()
Find positionsearch()
Replace textreplace()
Split textsplit()

Common Mistakes with RegExp Methods

  • Using exec() without understanding global flag behavior

  • Forgetting g flag when multiple matches are required

  • Expecting test() to return match details

  • Not escaping special characters

Summary of RegExp Methods

MethodBelongs ToPurpose
test()RegExpCheck if match exists
exec()RegExpReturn match details
match()StringGet matches
search()StringFind index
replace()StringReplace matches
split()StringSplit string

Conclusion

RegExp methods in JavaScript provide powerful tools for pattern matching and string manipulation. By using test() and exec() on RegExp objects and match(), search(), replace(), and split() on strings, text processing tasks like validation, searching, and transformation become efficient and easy to manage.