JavaScript | Regular Expressions

A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text 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 :



var patt = /GeeksforGeeks/i;

/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:

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:

Metacharacter Description
d Used to find a digit
s Used to find a whitespace character
 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:

Quantifier Description
n+ Used to match any string that contains at least one n
n* Used to match any string that ccontains 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 :

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/);



Use String replace() With a Regular Expression :
Use a case insensitive regular expression to replace gfG with GeeksforGeeks in a string:
Example :

function myFunction() {
    // input string
    var str = "Please visit gfG!";
    // replacing with modifier i 
    var txt = str.replace(/gfg/i, "geeksforgeeks"); 


Please visit geeksforgeeks! 

This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment



load comments

Subscribe to Our Newsletter