javascript

Regular Expression


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 (/.../).

 

Creating a Regular Expression:

 

Using Literal Notation: 

let regex = /pattern/;

 

Using RegExp Constructor:

let regex = new RegExp('pattern');

 

Basic Pattern Matching:

 

Characters:

let regex = /hello Coders/;

 

Metocharacters:

Special characters with special meanings like `^`, `$`, `.`, `*`, `+`, `?`, `\`, `()`, `[]`, `{}`, etc.

 

Flags:

 

  • Global (g): Searches for all matches within the string.
  • Case-insensitive (i): Ignores the case while matching.
  • Multiline (m): Allows ^ and $ to match the beginning and end of each line (not just the beginning and end of the whole string).

 

Methods:


1. `test()`: This method checks if a pattern exists in a string, returns true or false.

 

Syntax:

regex.test("string");

 

2. `exec()`: This method returns an array containing all matched groups or null if there are no matches.

 

Example:

regex.exec("string");

 

3. `match()`: This method returns an array containing all matches or null if there are no matches.

 

Example:

"string".match(regex);

 

4. `search()`: This method returns the index of the first match, or -1 if not found.

 

Syntax:

"string".search(regex);

 

5. `replace()`: This method replaces the matched substring(s) with a new substring.

 

Syntax:

"string".replace(regex, "replacement");

 

Example:

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"