JavaScript Regular Expressions
Below is the example of the JavaScript Regular Expressions.
- Example:
JAVASCRIPT
<script> function GFGFun() { var str = "Visit geeksforGeeks"; var n = str.search(/GeeksforGeeks/i); document.write(n); } GFGFun(); </script> |
- Output:
6
A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text to replace operations. A regular expression can be a single character or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations.
Syntax:
/pattern/modifiers;
Example:
var patt = /GeeksforGeeks/i;
Explanation:
/GeeksforGeeks/i is a regular expression.
GeeksforGeeks is a pattern (to be used in a search).
i is a modifier (modifies the search to be Case-Insensitive).
Regular Expression Modifiers :
Modifiers can be used to perform multiline searches:
Examples:
Expressions Description [abc] Find any of the character inside the brackets [0-9] Find any of the digits between the brackets 0 to 9 (x | y) Find any of the alternatives between x or y separated with |
Regular Expression Patterns :
Metacharacters are characters with a special meaning:
Examples:
Metacharacter Description \d Used to find a digit \s Used to find a whitespace character \b Used to find a match at beginning or at the end of a word \uxxxx Used to find the Unicode character specified by the hexadecimal number xxxxx
Quantifiers define quantities:
Examples:
Quantifier Description n+ Used to match any string that contains at least one n n* Used to match any string that contains zero or more occurrences of n n? Used to matches any string that contains zero or one occurrences of n
Using String Methods:
In JavaScript, regular expressions are often used with the two string methods: search() and replace().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
Using String search() With a Regular Expression :
Use a regular expression to do a case-insensitive search for “GeeksforGeeks” in a string:
Example:
JAVASCRIPT
<script> function myFunction() { // input string var str = "Visit geeksforGeeks!"; // searching string with modifier i var n = str.search(/GeeksforGeeks/i); document.write(n + '<br>' ); // searching string without modifier i var n = str.search(/GeeksforGeeks/); document.write(n); } myFunction(); </script> |
Output:
6 -1
Use String replace() With a Regular Expression :
Use a case insensitive regular expression to replace gfG with GeeksforGeeks in a string:
Example:
JAVASCRIPT
<script> function myFunction() { // input string var str = "Please visit gfG!"; // replacing with modifier i var txt = str.replace(/gfg/i, "geeksforgeeks"); document.write(txt); } myFunction(); </script> |
Output:
Please visit geeksforgeeks!