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.

JavaScript
1let regex = /cat/i;
2let text = "The Cat is here";
3
4console.log(regex.test(text));

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


exec()

Finds a match and returns details about the first match.

JavaScript
1let regex = /\d+/;
2let text = "Order 245 received";
3
4console.log(regex.exec(text));

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.

JavaScript
1let text = "red blue red green";
2console.log(text.match(/red/g));

Explanation:
Returns all occurrences of red as an array.


search()

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

JavaScript
1let text = "Learning JavaScript";
2console.log(text.search(/JavaScript/));

Explanation:
Returns the starting index of JavaScript.


replace()

Replaces matched text with new text.

JavaScript
1let text = "I like apples";
2console.log(text.replace(/apples/, "oranges"));

Explanation:
Replaces apples with oranges.


split()

Splits a string using a pattern.

JavaScript
1let text = "apple, banana, mango";
2console.log(text.split(/,\s*/));

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.