JavaScript RegExp Object
The regular expression or JavaScript RegExp is an object that helps you to validate the pattern of characters in a string or match a string, etc. You can use the JavaScript RegExp object to validate an e-mail entered in a form, or maybe check if a Pincode is all numeric, or a password has alphanumeric and special characters, etc.
There are two ways of defining regular expression in JavaScript.
1. Using the JavaScript RegExp object's constructor function
2. Using Literal syntax
Creating JavaScript RegExp Object
Let's see how we can create a RegExp object in JavaScript:
// Object Syntax
let regExp = new RegExp("pattern", "flag");
// Literal Syntax
let regExp = /pattern/flag;
Where the pattern is the text of regular expression, the flag makes the regular expression search for a specific pattern.
Note: In this tutorial, we will discuss the RegExp object, its properties and methods. All the examples will be based on the RegExp object, not the literal regular expression. We have covered the regex literal syntax earlier.
We will be using the following String methods to use the RegExp object to test, match, and validate various string values in JavaScript:
-
test()
-
match()
-
replace()
-
exec()
Let's take a few examples to understand the use of the JavaScript RegExp object.
Creating a RegExp to match IP address
To match all the strings that look like IP address: xxx.xxx.xxx.xxx, we can use the following regex pattern:
let regularexp = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g;
Now let's create an example to validate an IP address. The below code returns true if the given IP address is valid:
let str = "102.235.251.251";
// regex pattern to match valid ip
let re = new RegExp(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/);
// test the regex
let result = re.test(str);
if(result)
document.write("Ip address is valid");
else
document.write("Ip address is not valid");
Ip address is valid
How to replace a string using Regex?
Let's see an example to replace a part of the string or the complete string with some other string or replace the order of the string using a regular expression.
// Creating regex object
let re = new RegExp(/(\w+)\s(\w+)/);
let str = 'Mohan Shyam';
// Replacing string
let newstr = str.replace(re, '$2, $1');
document.write(newstr);
Shyam, Mohan
Fetch Subdomain Value from a Domain Name
We can use a regular expression to fetch the subdomain from a URL. The RegExp exec()
method is used to perform regular expression pattern matching, and return an array of string. See the below example:
let url = 'http://linux.studytonight.com';
// Creating regex object
let re = new RegExp(/[^.]+/);
let result = re.exec(url)[0].substr(7);
document.write(result);
linux
Find a Pattern in String
To find a pattern in string, we can use the string match()
method. It returns the match pattern that can be a substring. See the below example:
// Creating regex object
var regex = new RegExp(/India/g);
var str = "We live in India.";
// search for India
var matches = str.match(regex);
document.write(matches);
India
Properties of JavaScript RegExp Object
-
global: refers that g modifier is set.
-
ignoreCase: refers that i modifier is set
-
lastIndex: refers to the index to start the next match.
-
multiline: Refers that m modifier is set.
-
source: refers to the text of the RegExp pattern.
JavaScript RegExp ignoreCase
Property:
The ignoreCase
property indicates whether or not the i
flag is used with the regular expression. The ignoreCase
is a read-only property of the RegExp object.
var re = new RegExp("/hello/","i");
// ignorecase property
var result = re.ignoreCase;
document.write(result);
true
JavaScript RegExp Object Methods
Regex object provides various method to work with regular expressions. The below table contains its methods:
Method
|
Description
|
exec()
|
Executes a search for a match in a string. It returns an array of information or null on a mismatch.
|
test()
|
Tests for a match in a string. It returns true or false.
|
match()
|
Returns an array containing all of the matches, including capturing groups, or null if no match is found.
|
matchAll()
|
Returns an iterator containing all of the matches, including capturing groups.
|
search()
|
Tests for a match in a string. It returns the index of the match, or -1 if the search fails.
|
replace()
|
Executes a search for a match in a string, and replaces the matched substring with a replacement substring.
|
split()
|
Uses a regular expression or a fixed string to break a string into an array of substrings.
|
RegExp test()
Method Example
The RegExp test()
method is used to test the regular expression and it returns true if the expression matches.
<script>
var str = "Hello";
var re = new RegExp("/hello/","i");
var result = re.test(str);
document.write(result)
</script>
true
Validate Email using Regular Expression
Let's validate an email address by using a regular expression. In the below example, we are validating email for the user to ensure that user enters valid email only.
let str = "abc@gmail.com";
// regex pattern to match valid email
let re = new RegExp(/^\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