JavaScript Regular Expression – How to Create & Write them in JavaScript

Free Web development courses with real-time projects Start Now!!

The last tutorial on JavaScript Characters was interesting, wasn’t it? The same concept extends to a little advance level in this tutorial. Here, in this article, we will implement everything that we have learned in our previous tutorial. It isn’t that difficult, all you need to do is remember all the special characters, and their uses from our previous tutorial. We won’t say you to learn them by heart with a single read, but at least you must understand the basics. Thus, you can’t understand about JavaScript Regular Expression without having basic knowledge about JavaScript Characters.

After knowing about JavaScript Characters, let’s continue with our tutorial on JavaScript Regular Expression, we’ll provide you with numerous real-life examples to lead you through the concept.

How to write JavaScript Regular Expression

What is a JavaScript Regular Expression?

A JavaScript Regular Expression is an object, describing a pattern of characters in JavaScript. These help to match character combinations in a String. To make things easier for you, JavaScript also provides a regular expression object. Let’s try to understand it with something we can relate to.

For Example

Suppose I have a text sentence, “Hello, this is DataFlair’s JavaScript tutorial”, and I want to search if it contains the word “Hello”. How would I proceed? Easy, I’ll search for an h followed by an e, then ll which is followed by a vowel o again. JavaScript computes things the same way: it searches for a pattern in the string.

Remember, a regular expression can be either a single character or a pattern of multiple characters. We can perform all sorts of text find and replace operations with their help.

You must go through our tutorial on JavaScript Strings, it will surely help you to make your understanding easier.

How to Create JavaScript Regular Expression

There are two approaches to create a regular expression in JavaScript.

1. Using a regular expression literal

The script compiles regular expression literals when it loads in the memory. These improve the performance of a program marginally if the expression remains constant. A regular expression in JavaScript consists of a pattern wrapped with the slashes and the syntax is as follows:

var re = /regular expression/;

2. Using the constructor function

It provides runtime compilation of the regular expression and is an excellent way when the expression value changes regularly. Or it may be that you aren’t sure of the pattern since you are retrieving it from an outside source, including user input. You can call the constructor function of the RegExp object with the help of the following syntax:

var re = new RegExp('regular expression');

How to Write JavaScript Regular Expression

Remember, while going through our tutorial, Introduction to JavaScript, we said that JavaScript provides the additional feature of email validation on the browser itself? Well, in this JavaScript tutorial, we will understand how we can perform it with the help of regular expressions. I want the user to enter an email address and JavaScript to perform validation. We will build up the concepts and at the end of this tutorial, will validate the email with a JavaScript code. The following are the basic components we need to work with regular expressions:

1. Using simple patterns

We use these patterns in case we want a direct match. Thus if I wanted to validate a password, this method is just what I need. The simple pattern will return true only if the characters are in the exact order and all the letters have the same case as required. But, this approach isn’t suitable for my task of email validation. Well, no issues, JavaScript got something else for you to use in this situation: special characters.

2. Using special characters

You can include special characters (always the lifesavers) for searches that require more than a direct match. I know one thing that all emails have in common: a series of letters and the @ sign followed by a series of letters, a dot and then again a set of letters. So what I need to do is search for this pattern and if the pattern holds in my string? Bam! I got a valid email address. If not, well, I just inform the user that the email entered is invalid. Okay, I’m not talking gibberish, we will implement this concept later in the tutorial. We learned about all the special characters we need in our prior tutorial.

3. Escaping

Suppose you want to use a special character literally; what would you do now? That’s right, we will use escape characters, starting with a backslash (\), to do that. We add a backslash before each special character to make them literals. For example, you can search for an expression a*b in your string with the help of the following code:

var re = /a\*b/

4. Using parentheses

Parentheses around any JavaScript character or expression indicate that the content of the parentheses is a ‘Capturing Group’. This group stores the matched substring in a separate array. Also, if we add a quantifier after the parentheses, it applies to the entire parenthesis and not just the last character. The interpreter processes the contents of parentheses from left to right. We use non-capturing groups, parentheses with the preface ?: to avoid remembering the matched substring.

We will use parentheses in our program for email validation, but let’s take a simple regular expression to understand the use of parentheses.

In the example below, the + quantifier applies on the whole substring “ppi” rather than just “i”.

var name = "Mississippi"
name.match(/(ppi+)/)
// (2) ["ppi", "ppi", index: 8, input: "Mississippi", groups: undefined]

Output:

JavaScript Regular Expression using parentheses

Don’t forget to explore the article on JavaScript Array

Working with JavaScript Regular Expressions

To work with regular expressions in JavaScript, we use the following RegExp and String methods:

MethodDescription
exec()
It is a RegExp method, executes a search for a match in a string and returns an array of information or a NULL on mismatch.
test()
It is a RegExp method, tests for a match in a string and returns true or false.
match()
It is a String method that returns an array containing all the matches or NULL if no element matches.
matchAll()
It is a String method returning an iterator containing all the matches.
search()
It is a String method, tests for a match in the string and returns the index of the match if present, else -1.
replace()
This String method searches for a match in a string and replaces it with the replacement string.
split()
This String method breaks a string into an array of substrings using a regular expression or a fixed string.

Let’s test these methods in our respective browser consoles. Define the following values first:

  • var string = “This is DataFlair’s JavaScript tutorial”
  • var myRe = /a[a-z]a/

Code:

myRe.exec(string)
// ["ata", index: 9, input: "This is DataFlair's JavaScript tutorial", groups: undefined]
myRe.test(string)
// true
string.match(myRe)
// ["ata", index: 9, input: "This is DataFlair's JavaScript tutorial", groups: undefined]
string.matchAll(myRe)
// RegExpStringIterator {}
string.search(myRe)
// 9
string.split(myRe)
// (3) ["This is D", "Flair's J", "Script tutorial"]

Output:

Working with JavaScript Regular Expressions - myRe.exec

RegExp Properties

The most common properties of a RegExp object are as follows:

PropertyDescription
global
This property specifies if the “g” flag is set.
ignoreCase
It specifies if the “i” flag is set.
lastIndex
It indicates the index at which to start the next match.
multiline
This property specifies if the “m” flag is set.

Validating Emails with Regular Expressions

Finally, we’ve come to the part where we start validating email addresses. Isn’t it cool? I hope you have a basic understanding of what regular expressions in JavaScript are. Keep scanning the different characters associated with regular expressions and their functions in the beginning. Eventually, you won’t need to turn back to the list for every character. As you practice, you’ll be able to master them and use them without consulting. The code to validate email addresses using JavaScript is as follows:

Code:

<html>
  <body>

    <script>
      var email = prompt("Enter an email address");
      var myRe = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; // regular expression for validation
      var checkEmail = myRe.exec(email); // check validity using myRe
      if(checkEmail){
        document.write("You entered the email: " + email);
      }else{
        document.write("This is not a valid email address.");
      }

    </script>

  </body>
</html>

Screenshot:

Validating emailwith javascript regular expression

Prompt:

JavaScript Regular Expression email prompt1

Output (when I enter invalid email address):

JavaScript Regular Expressionemail op1

Output (when I enter a valid email address):

JavaScript Regular Expressionemail op2

Summary

Here we conclude our tutorial on JavaScript Regular Expression. In this article, we learned what regular expressions are and how to create and work with them in JavaScript. We also went through the various terminologies associated with regular expressions. Lastly, we created a JavaScript program using regular expressions to validate an email address.

Next, you must go through our article on JavaScript Dataview

Hope the information provided was fruitful to you. If you still have any queries, do share with us through the comment section.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

courses

DataFlair Team

DataFlair Team specializes in creating clear, actionable content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Backed by industry expertise, we make learning easy and career-oriented for beginners and pros alike.

1 Response

  1. Gethin LW says:

    FYI that’s a poor regex for validating email addresses (it misses **many** valid addresses). Use the one described in this post instead: https://stackoverflow.com/a/201378/13305584

Leave a Reply

Your email address will not be published. Required fields are marked *