JavaScript

JavaScript RegEx Example

Greetings readers, in this tutorial, we will understand and implement the regular expressions in the javascript language.

1. Introduction

JavaScript is an object-oriented programming language that allows the client-side scripting to interact with a user and deliver the dynamic pages. Most web browsers including Google Chrome, Mozilla Firefox, Safari, Internet Explorer, Microsoft Edge, Opera, etc. support it. The JavaScript scripting language includes:

  • Declaring variables
  • Maintaining the retrieving values
  • Defining and invoking functions
  • Defining classes
  • Load and use external modules
  • Define event handlers
  • And much more ….

1.1 Advantages of JavaScript Language

The pros of using the JavaScript scripting language are:

  • JavaScript is easy to learn
  • It executes on client’s browser, so eliminates the server-side processing and be executed on any OS
  • JavaScript can be used with any type of web page e.g. PHP, ASP.NET, Perl etc
  • Web-page performance increases due to client-side execution
  • JavaScript code can be minified to decrease the loading time from the server
  • Many JavaScript-based application frameworks are available in the market to create Single page web applications e.g. AngularJS, ReactJS etc.

1.2 Disadvantages of JavaScript Language

The cons of using the JavaScript scripting language are:

  • Does not have any multi-threading or multi-processing capabilities
  • Does not allow the file reading and writing capabilities

1.3 Regular Expressions (RegEx) in JavaScript Language

A Regular Expression in javascript represents a sequence of character that defines a search pattern. A regular expression can be a sole character or a complex pattern and is principally used to perform the text-search and the text-replace operations.

1.3.1 Syntax

The following snippet represents the regular expression syntax in the javascript language.

// Constructor notation of the regular expression object.
var mypattern = new RegExp(my_regular_expression_pattern, attributes);

// Or,

// Literal notation of the regular expression.
var mypattern = /my_regular_expression_pattern/attributes

Where:

  • new RegExp() constructor defines a regular expression
  • my_regular_expression_pattern is a string that defines the pattern of a regular expression
  • attributes is an optional string that specifies the global (‘g’), case-insensitive (‘i’), and multi-line (‘m’) matches respectively

1.3.2 Trailing notes

Always remember,

  • The literal notation is convenient and makes the regular expressions easier to read
  • To test whether a regular expression matches a specific string, developers can use the RegExp.test() method
  • To extract the information from a string using the regular expression, developers can use the RegExp.exec() method

2. JavaScript RegEx Example

Here is a systematic guide for implementing this tutorial using the javascript language.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure if you are confused about where you should create the corresponding files or folder later!

JavaScript RegEx - Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will show on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

JavaScript RegEx - Create a Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

JavaScript RegEx - Project Details
Fig. 3: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

JavaScript RegEx - Archetype Selection
Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

JavaScript RegEx - Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javascript.regularexpressions</groupId>
	<artifactId>JavascriptRegex</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

3. Application Building

Let us create an application to understand the basic building blocks of this tutorial.

3.1 Define the HTML

Let us write a simple index page in the JavascriptRegex/src/main/webapp/ folder. Add the following code to it.

index.jsp

<!-- Javascript regular expressions tutorial -->
<div id="title">
	<form id="usersignup">
		<input type="text" class="form-control" name="username" placeholder="Enter username . . .">
		<p>Username between 5 and 10 characters.</p>

		<input type="password" class="form-control" name="password" placeholder="Enter password . . .">
		<p>Password between 8 and 10 alphanumeric characters; can contain special characters (@, _ or -).</p>

		<input type="text" class="form-control" name="email" placeholder="Enter email . . .">
		<p>Doesn't look like a valid email (E.g. me@mydomain.com).</p>

		<input type="text" class="form-control" name="telephone" placeholder="Enter telephone . . .">
		<p>Phone number should be 10 digit number.</p>
	</form>
</div>

3.2 Define the JavaScript function

Let us write a simple javascript function that will help developers understand the different regular expression patterns in the javascript language. In this tutorial, we will perform the form validation based on the given pattern and these validations will trigger on a ‘blur’ event. Add the following code to it.

JavaScript function

const inputs = document.querySelectorAll('input');

// Regular expressions patterns.
const patterns = {
	username: /^[a-z\d]{5,10}$/i,
	password: /^[\d\w@-]{8,10}$/i,
	email: /^([a-z\d\.-]+)@([a-z\d-]+)\.([a-z]{2,8})(\.[a-z]{2,8})?$/,
	telephone: /^\d{10}$/
};

// Validation functions.
function validate(field, regex) {
	if (regex.test(field.value)) {
		field.className = 'valid';
	} else {
		field.className = 'invalid';
	}
}

// Attaching blur event to the input fields.
inputs.forEach((input) => {
	input.addEventListener('blur', (e) => {
		validate(e.target, patterns[e.target.attributes.name.value]);
	});
});

3.3 First application

Complete the above steps and save the file. Let us see the sample code snippet.

index.jsp

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Index page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9zdGFja3BhdGguYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.1.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/mystyle.css">
</head>

<body>
    <div class="container">
        <h2 align="center" class="text-danger">Regular Expressions in JavaScript</h2>
        <hr />

        <!-- Javascript regular expressions tutorial -->
        <div id="title">
            <form id="usersignup">
                <input type="text" class="form-control" name="username" placeholder="Enter username . . .">
                <p>Username between 5 and 10 characters.</p>

                <input type="password" class="form-control" name="password" placeholder="Enter password . . .">
                <p>Password between 8 and 10 alphanumeric characters; can contain special characters (@, _ or -).</p>

                <input type="text" class="form-control" name="email" placeholder="Enter email . . .">
                <p>Doesn't look like a valid email (E.g. me@mydomain.com).</p>

                <input type="text" class="form-control" name="telephone" placeholder="Enter telephone . . .">
                <p>Phone number should be 10 digit number.</p>
            </form>
        </div>
    </div>
    <script>
        const inputs = document.querySelectorAll('input');

        // Regular expressions patterns.
        const patterns = {
            username: /^[a-z\d]{5,10}$/i,
            password: /^[\d\w@-]{8,10}$/i,
            email: /^([a-z\d\.-]+)@([a-z\d-]+)\.([a-z]{2,8})(\.[a-z]{2,8})?$/,
            telephone: /^\d{10}$/
        };

        // Validation functions.
        function validate(field, regex) {
            if (regex.test(field.value)) {
                field.className = 'valid';
            } else {
                field.className = 'invalid';
            }
        }

        // Attaching blur event to the input fields.
        inputs.forEach((input) => {
            input.addEventListener('blur', (e) => {
                validate(e.target, patterns[e.target.attributes.name.value]);
            });
        });
    </script>
</body>

</html>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

JavaScript RegEx - Deploy Application on Tomcat
Fig. 6: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL to display the application’s index page as shown in Fig. 7.

http://localhost:8082/JavascriptRegex/

Server name (localhost) and port (8082) may vary as per your Tomcat configuration.

JavaScript RegEx - Index page
Fig. 7: Index page

Users can click on the individual form fields to trigger the validations upon the blur event as shown in Fig. 8.

JavaScript RegEx - Regular Expression validations
Fig. 8: Regular Expression validations

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy learning and do not forget to share.

6. Conclusion

In this section, developers learned how to create a simple application with the JavaScript language. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was a beginner’s tutorial to understand and implement the regular expressions in the javascript language.

Download
You can download the full source code of this example here: JavascriptRegex

Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button