Signup/Sign In

JavaScript Regular Expression

In JavaScript, Regular Expressions also known as regex are patterns used to match, replace, compare character combinations in strings.

When we search for some specific data in a text, we can use regular expression to be used as search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.

We can use regex to perform any type of text search and text replace operations.

There are two different ways of using a regular expression in JavaScript, they are:

  1. Using RegExp object's constructor function

  2. Using Regular Expression Literal

In this tutorial we will cover the Regular expression literal and will cover the RegExp object in detail when we cover JavaScript objects.

JavaScript Regular Expression Literal: Syntax

We can use a regular expression literal, which consists of a pattern enclosed between slashes, as follows:

/pattern/modifiers;

Regular expression literals compiles at the time of script loading.

In the above syntax, pattern can be any text or string combination wheras modifiers/flags are provided by Javascript. Some flags are given below.

Flag

Description

i

It is used to perform case-insensitive search.

g

It is used to search for all matches, without it – only the first match is returned.

m

Search for multiline mode.

s

Enables “dotall” mode, that allows a dot . to match newline character \n.

u

Enables full unicode support.

y

Searching at the exact position in the text.

Mostly a regular expression is used to validate a string against a pattern or extract a specific substring out of a string or check if a string contains a certain substring, and for checking this, we use the RegExp.test() function.

JavaScript String test(), replace() and match() Functions:

The test() function is used along with a regular expression pattern providing a string as an argument. The syntax for using the test() function is:

let re = "/SOME-EXPRESSION/";
let str = "some string";
// using test() function
let result = re.test(str);    // returns true on match else false

Just like we have used the test() function in the example above to check if a particular string pattern is present in a given string, similarly we use replace() function when we have to replace a string pattern with some other string value and match() function to match and returned the match string.

Let's see a few example to understand how we can use regular expression in JavaScript.

Search Using Regex Literal

Lets search for the string "hello" using the regex lilteral in any given string. See the below code example:

<script>
	let re = /hello/;
	let str = "Hello Studytonight";
    // test() function is used with regular expression
	let result = re.test(str);
	document.write(result)
</script>


false

In the above example, we performed a search, to look for a substring pattern in a given string. Here, we did not use any flag, so by default a case sensitive search was performed, that's why we got the result as false.

Search Using Regex Literal - Ignore Case

We can perform a search while ignoring the case of the string too, if we want to search for a possible pattern, and we are not looking for an exact match. For performing case insensitive search in a string using regular expression, we will use the i flag that will enable ignore case for the search. See the below example:

<script>
	let re = "/hello/i";
	let str = "Hello Studytonight";
	let result = re.test(str);
    // use console.log or document.write
	document.write(result);
</script>


true

Replace String Using Regex

In this example, we will be replacing a string pattern with another string. To replace the string we will use the replace() method of string object and not the test() method.

<script>
		// Creating regex literal
	    let re = "/(\w+)\s(\w+)/"
        let str = 'Delhi Noida';
        // Replacing string
        let newstr = str.replace(re, '$2, $1');
        document.write(newstr);
</script>


Noida, Delhi

Search for a Pattern in the String

Here, we are searching using match() method. This method returns the matched string if there is a match. See the below example:

<script>
		// Creating regex literal
		var regex = "/India/g";
        var str = "We live in India.";
        // search for india
        var matches = str.match(regex);
        document.write(matches)
</script>


India

JavaScript Regex Literal: Validate an Email

Regular expressions in JavaScript are use for validating input form values like email address, password, zipcode or any other value.

Let's create a regular expression to validate an email address and use it to check if given email address is valid or not. You can easily find regular expressions to validate various types on inputs on the Internet.

let str = "abc@gmail.com";
// regex pattern to match valid email
let re = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/
// test the 
let result = re.test(str);
if(result)
    document.write("Email is valid")
else
    document.write("Email is not valid")


Email is valid

In this tutorial, we learned about regular expressions and how we can use them in JavaScript for matching string patterns, replacing strings, validating user inputs etc. What we have learned here is the literal way of creating a regular expression(just like in array there are two ways), we can also create a regular expression object using the regular expression prototype in JavaScript. We will learn about it when we will cover the JavaScript Objects.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight