javascript

String Methods for matching patterns


JavaScript's String object provides several methods for matching patterns using regular expressions.

 

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.

 

Syntax:

regex.exec("string");

 

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

 

Syntax:

"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 matches 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"

regex.toString();