Regular Expression
Syntax: /pattern/modifiers;
pattern - the string pattern that needs to be searched
modifiers - the condition if any during the search for the pattern.
Regular Expression Modifiers:
i - Perform case-insensitive matching
g - Perform a global match (find all matches rather than stopping after the first match)
m - Perform multiline matching
Regular Expression Patterns:
[abc] - Find any of the characters between the brackets
[0-9] - Find digits in the range in the brackets
[x|y] - Find x or y giving in the bracket
Metacharacters:
Quantifiers:
______________________________________
Regular expressions can be used with 2 of String methods:
1)str.search(""); //returns index of first occurence
Example:
- var str = "Visit W3Schools";
- var n = str.search(/w3schools/i); // returns 6
2)str.replace(""); //returns string by replacing string occurence
Example:
- var str = "Visit Microsoft!";
- var res = str.replace(/microsoft/i, "W3Schools"); //returns Visit W3Schools! for "res" value
______________________________________
Regex Object and its methods:
test(): It searches a string for a pattern, and returns true or false, depending on the result.
- var patt = /e/;
patt.test("The best things in life are free!");
- (or)
- /e/.test("The best things in life are free!");
- Results in "true"
exec(): It searches a string for a specified pattern, and returns the found text. If text not found, returns null;
- /e/.exec("The best things in life are free!");
- Results in "e"
______________________________________