Regular expressions are used for pattern matching within strings. They allow you to search for specific patterns of characters within a larger string, extract information, or replace parts of the string based on certain criteria.
In JavaScript, you create regular expressions by using the RegExp constructor or by using a literal notation with slashes (/.../).
let regex = /pattern/;
let regex = new RegExp('pattern');
let regex = /hello Coders/;
Special characters with special meanings like `^`, `$`, `.`, `*`, `+`, `?`, `\`, `()`, `[]`, `{}`, etc.
1. `test()`: This method checks if a pattern exists in a string, returns true or false.
regex.test("string");
2. `exec()`: This method returns an array containing all matched groups or null if there are no matches.
regex.exec("string");
3. `match()`: This method returns an array containing all matches or null if there are no matches.
"string".match(regex);
4. `search()`: This method returns the index of the first match, or -1 if not found.
"string".search(regex);
5. `replace()`: This method replaces the matched substring(s) with a new substring.
"string".replace(regex, "replacement");
var regex = /hello/;
regex.test("hello Coders"); // true
regex.test("hi there"); // false
var regex2 = /\d+/; // find digits
regex2.exec("I have 3 apples"); // ["3"]
var regex3 = /apple/g;// find all apple
"I have three apples and one apple pie".match(regex3); // ["apple", "apple"]
var regex4 = /apples?/; // apple exist?
"I have three apples and one apple pie".replace(regex4, "orange");
// "I have three oranges and one orange pie"