Table of contents
1.
Introduction
2.
Regular Expressions in JavaScript
2.1.
Creating a Regular Expression
2.2.
Testing for Matching
2.3.
Using Pattern Flags
2.3.1.
1) The Ignore Flag
2.3.2.
2) The Global Flag
2.4.
Searching Strings
2.5.
Replacing String
3.
RegExp Object and Features
3.1.
Modifiers
3.2.
Brackets
3.3.
Metacharacters
3.4.
Quantifiers
3.5.
RegExp Object Properties
3.6.
RegExp Object Methods
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Regex in Javascript

Author Naman Kukreja
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The programmer or developer learning web development must have encountered javascript once in his learning or working phase. Javascript is a crucial language to know to make their project responsive earlier, which was containing only CSS and HTML.

There is n number of functions and properties available in javascript, but some of them are most necessary as they make the developer's work relatively easy. One of the functions is regex. With the help of this, we can perform many operations with and on the regular expression.

We will learn all about regex in javascript while moving further with the blog, so let's get on with our topic without wasting any time further.

Regular Expressions in JavaScript

Regular expressions are strings that describe patterns, such as email addresses and phone numbers.

Regular expressions are objects in Javascript. The built-in RegExp type in JavaScript enables you to deal efficiently with regular expressions.

Regular expressions may be used to find and replace strings that match a specific pattern. They may be used in a variety of ways.

Regular expressions, for example, may be used to extract meaningful information from web scraping, such as product pricing. Regular expressions may also be used to verify form fields such as email addresses and phone numbers.

Creating a Regular Expression

In JavaScript, we generate a regular expression by enclosing its pattern in forward-slash characters (/), as seen here:

let re = /hi/;

Or you can also use the inbuilt constructor like this:

let re = new RegExp('hi');

Both these expressions match the string ‘hi’.

Testing for Matching

Many helpful methods are available in the RegExp object. One of them is the test() function, which let us see whether a string matches the regular expression pattern.

If the string argument has a match, the test() function returns true.

The test() function is used in the following example to see whether the string 'hi John' fits the pattern hi:

let re = /hi/;
let result = re.test('hi John');

 
console.log(result); // true

Using Pattern Flags

A RegExp object allows an extra flag argument in addition to a pattern. Flags are options that alter the way the search engine works. There are a lot of flags in regular expressions.

1) The Ignore Flag

When searching, the i flag excludes cases. Ignore is represented by the letter i.

Searches are case-sensitive by default. For instance, /hi/ matches just the string hi, not Hi. The i flag is used to search for the string hi in any case:

let re = /hi/i;
let result = re.test('Hi John');

 
console.log(result); // true

In this case, the /hi/i will match any string that begins with the letters hi, Hi, or HI. It's worth noting that the flag i is placed after the final forward-slash character (/).

How to utilise the flag in the RegExp function Object() is shown in the following example:

let re = new RegExp('hi','i');
let result = re.test('HI John');

 
console.log(result); // true

2) The Global Flag

The Global flag is another widely used flag (g). The RegExp object only looks for a match in a string and returns the first match if the global flag is not set.

When the g option is set, the RegExp searches for all possible matches and returns them all.

Flags may be combined. For example, gi flags combine the ignore (i) and global (g) flags.

The RegExp's exec() function searches a text for a match and returns an array with extensive information about the match.

If no match is found, the exec() function returns null. However, it only returns one match at a time. You'll need to run exec() many times to obtain all matches.

To return all matches, the following example uses the exec() function in conjunction with a do-while loop:

let message = 'Hi, are you there? hi, HI...';
let re = /hi/gi;

 
let matches = [];
let match;
do {
    match = re.exec(message);
    if(match) {
      matches.push(match);
    }
} while(match != null)

 
console.dir(matches);

Output:

You can compile with the help of Online Javascript Compiler for better understanding.

Searching Strings

The str.match(regexp) function retrieves all regexp matches in the string str.

The global flag is used to locate all matches (g). You may also use the ignore flag to locate matches regardless of case (i).

The match() function is shown in the following example:

let str = "Are you Ok? Yes, I'm OK";
let result = str.match(/OK/gi);

 
console.log(result);

Output:

Replacing String

In the example below, we will replace all the string 'OK' occurrences in the string str by using the replace() function.

let str = "Are you OK? Yes, I'm OK.";
let result = str.replace('Ok','fine');

 
console.log(result);

Output:

To replace all the occurrences of 'OK,' we will use the global flag g in our expression.

let str = "Are you OK? Yes, I'm OK.";
let result = str.replace(/OK/g,'fine');

 
console.log(result);

Output:

You can use both global and ignore flags to replace all the occurrences of the 'OK' with fine no matter the case, like shown in the below example:

let str = "Are you OK? Yes, I'm OK.";
let result = str.replace(/OK/gi,'fine');

 
console.log(result);

Output:

RegExp Object and Features

These are the pattern of characters and are used to do pattern matching, replacing, and searching, and in javascript, the RegExp object is a pattern with methods and properties.

We will learn about all its feature in this part of the blog.

Modifiers

They are used to perform global and case insensitive searches:

Brackets

They are used to find the range of characters:

Metacharacters

These are the special characters with special meaning:

Quantifiers

These are the unique set of characters or symbol which has special function and meaning:

RegExp Object Properties

These are some properties of the regular expression with specific meaning.

RegExp Object Methods

These are certain object methods used while working with a regular expression:

FAQs

  1. What is the function of $ in regex?
    $ is used to match the end of the line in regex.
     
  2. What is the primary requirement of regex in javascript?
    The primary requirement of regex in javascript is extracting and parsing data from text to a specific pattern.
     
  3. How many types of the regex are there in javascript?
    There are mainly two types of regex available in javascript, and they are essential and extended.
     
  4. What is the use of multiline property in regex?
    It checks whether the "m" modifier is set or not.

Key Takeaways

In this article, we have extensively discussed regex in javascript, regular expression in javascript with various functions we can perform like creating a regular expression, testing expression, searching, and replacing. Along with that, we have also discussed regex object and their features with different properties, modifiers, brackets, and much more.

We hope that this blog has helped you enhance your knowledge of regex in javascript. If you are interested in learning more about regular expressions in javascript, then you must visit this blog. There you will get a complete idea about regular expressions with built-in methods and pattern matching for regular expressions and much more. If you would like to learn more, check out our articles on Code studio. Do upvote our blog to help other ninjas grow.

 “Happy Coding!”

Live masterclass