A Brief Introduction To Regular Expressions In Javascript

Posted By : Pushpandra Kumar | 30-May-2018
A regular expression provides a quick way of matching any string to a pattern. For example, we can write a regular expression of a phone number and can check whether a particular given number is a valid phone number or not.
Regular expressions use some special characters to detect a particular pattern. In JS, regular expressions are also objects. 
 
Creating a Regular Expression in JS 
we can create a regular expression with a string enclosed between backslashes.
e,g. 
     var re = /ab+c/ ;
 
or we can use a RegExp object to create a regular expression. 
Syntax :
    ReqExp1 = new RegExp("Expression"); 
    RegExp2 = /Expression/;
 
e.g,
   var re = new RegExp('ab+c');
 
When we use RegExp constructor while creating any regular expression the pattern must be written as any normal string.
 
Writing Simple Patterns
 
1. Using Simple Patterns
     matches a string directly with the pattern.
     e.g, /klj/ matches a pattern containing characters klj together.
 
2. Using Special Characters
     when we want to search for more than a direct match, e.g, finding a number of lines or number of whitespaces.
     e.g, /\n/ will a new line
 
3. Using Parenthesis
     Allows a part of the matched substring to be remembered. 
 
Useful Methods while working with a regular expression: 
 
1. exec
This method starts the search for a match in any string. Then in the result, it returns null or array of information when there is any mismatch.
 
2. test
This method starts the search for the match in any string but it returns true or false.
 
3.search
This method too searches for the match and returns the index when matched and return -1 when mismatched.
 
4.replace
This method starts the search for the match and it replaces that particular substring with the required substring.
 
5.Split
This method uses a regular expression to break any string into an array of substrings. 
 
Example, To Count the number of lines using a regular expression,  
                                 console.log(("line 1.\nline 2.\nline 3.\nline 4.\nline 5.").split(/\n/).length);

About Author

Author Image
Pushpandra Kumar

Pushpender has experience in Core Java, C & C++. His hobbies are learning new technologies and listening music.

Request for Proposal

Name is required

Comment is required

Sending message..