Open In App

How useful is learning regular expressions in JavaScript ?

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

RegExp(Regular Expression) is a feature introduced in ES6 JavaScript which can be used to find a particular pattern or replace a pattern in a string. RegExp literals are compiled when the script is loaded, this increases the performance. The lines of code can be reduced if we use the RegExp format. Hence, it is used for efficient text processing.

There are two ways in which we can create a regular expression:

  • Regular expression literal: The pattern is enclosed between slashes
var regLiteral = /pattern/
var regConstructor = new RegExp('pattern');

Learning RegExp is useful as it prevents writing complex code for finding characters. The most common use of RegExp is in email format checking. It can be used for replacing characters in a string also we can use it for creating a password character matcher to ensure a strong password is created.

The two anchors ‘^’ and ‘$’ are used to match the position of characters at the beginning and end respectively. ‘^’ behaves differently when it is used in [] notation. Here, it acts as a negated character class and will then match any character that is not in the square brackets.

Now we will see examples in which regular expressions simplify the code. 

In the examples, we will use the test() method to validate the string against the RegExp. The method will return true if the string passes the test else it will return false.

Example 1: In this example,  we will see a basic code that checks whether a string contains numbers or not.

Javascript




var test1 = "This is a string without number";
var test2 = "I contain number 123";
  
// Without RegExp
function containsNumber(text) {
    for (var i = 0; i < text.length; i++) {
        if (Number.isInteger(parseInt(text[i]))) {
            return true;
        }
    }
    return false;
}
  
console.log(containsNumber(test1));
console.log(containsNumber(test2));
  
// With RegExp
function containsNumberRegEx(text) {
    return /[0-9]/.test(text);
}
  
console.log(containsNumber(test1));
console.log(containsNumber(test2));


Output:

false
true
false
true  

Explanation: We can see that both the functions check whether the string contains a number but with RegExp the lines of code have been reduced which makes writing code easy also the literal notation helps in faster execution of code.

Example 2: In this example, we will use RegExp to verify if the password is strong or not. A password is strong if it contains alphabets both in lower and upper case as well as special characters.

Javascript




var regChecker = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W).{8,}$/g
var pass1 = "guardian";
var pass2 = "Guardian123";
var pass3 = "Guardian123@";
  
function passCheck(text){
    if(regChecker.test(text)){
        return "Password is strong";
    }
    return "Password is weak";
}
  
console.log(passCheck(pass1));
console.log(passCheck(pass2));
console.log(passCheck(pass3));


Output:

Password is weak
Password is weak
Password is strong

Explanation: Here the RegExp verifies the password string and checks if it contains all the required characters. [a-z] checks for lowercase letters, [A-Z] checks for uppercase letters, \d checks for numbers, \W checks for symbol,s, and {8,} ensures that length is at least 8 characters.

Example 3: In this example, we will use RegExp to verify whether the email is valid or not

Javascript




var regChecker = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
var email1 = "111&xyz.com";
var email2 = "Guardian123$gmail.com";
var email3 = "Gu123@yahoo.com";
  
// Using RegExp to validate email
function mailCheck(text){
    if(regChecker.test(text)){
        return "Email is correct";
    }
    return "Invalid email";
}
  
console.log(mailCheck(email1));
console.log(mailCheck(email2));
console.log(mailCheck(email3));


Output:

Invalid email
Invalid email
Email is correct

Explanation: We can see that only the string which is in proper email format is validated. The regex expression first checks for an alphanumeric string and then looks for an “@” symbol. After that domain name is checked then a “.” symbol is searched with the following alphanumeric.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads