Understanding the Basics of Structural Design Patterns in JavaScript

Introduction

Structural design patterns are used to solve problems related to the composition of objects and their relationships. They help to organize code into larger structures, making it easier to maintain and modify.

Concerned with how objects are made up and simplify relationships between objects.

The four most common structural design patterns in JavaScript are:

  1. Adapter Pattern: The Adapter pattern allows objects with incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces, making them compatible.
  2. Decorator Pattern: The Decorator pattern adds functionality to an object dynamically without changing its original structure. It is used to extend the functionality of an object at runtime.
  3. Facade Pattern: The Facade pattern provides a simplified interface to a complex system. It acts as a high-level interface that makes it easier to use a complex system by providing a simplified interface to it.
  4. Flyweight Pattern: The Flyweight Pattern is useful when an application needs to create a large number of similar objects that differ only in some small aspects. By sharing the common properties, it reduces the memory footprint of an application and improves performance.

Adapter Pattern

The Adapter Pattern is a structural design pattern that allows objects with incompatible interfaces to work together by creating an adapter that acts as an intermediary between the two objects. The adapter translates the interface of one object into an interface that the other object can understand.

Adapter Pattern introduces an intermediary piece of code that makes two parts of a system compatible with one another.

Let’s say we have an existing class that provides a certain interface, but we want to use that class in a new context where it needs to conform to a different interface. We can use the Adapter Pattern to create a new class that adapts the existing class to the new interface.

Now understand Adapter Pattern with an example and here we are going to explain an example in steps:

Building Better Objects with Creational Design Patterns in JavaScript

As a JavaScript developer, you know that creating and managing objects can be a challenging task, especially as your projects grow in complexity. That’s where creational design patterns come in – they provide a proven blueprint for object creation that can help you write more efficient, scalable, and maintainable code.

In this blog post, we’ll explore the world of creational design patterns in JavaScript and discover how they can help us build better objects. We’ll start by introducing the basics of creational design patterns, discussing their advantages and disadvantages, and exploring some common patterns like the factory pattern, the builder pattern, and the singleton pattern.

By the end of this post, we’ll have a solid understanding of how to use creational design patterns to create more flexible and reusable objects, improve the performance and reliability of our code, and take our JavaScript skills to the next level. So, let’s get started!

In this post, we are going to start with Factory Pattern then after we will cover other patterns one by one :

Factory Pattern

The Factory Pattern is a creational design pattern that provides an interface for creating objects but allows subclasses to alter the type of objects that will be created. This pattern is often used when you need to create a large number of similar objects, or when the process of creating an object is complex and involves a lot of boilerplate code.

Factory Pattern is used to simplify Object Creation.

In JavaScript, the Factory Pattern is typically implemented using a factory function, which is a function that returns an object. The factory function can take arguments and use them to customize the object that it creates.

How to Create Factory Pattern in Javascript?

To Create a Factory Pattern in Javascript we need to follow the following steps:

Step 1: Creating a Factory Function

To create a factory function, we’ll need to define a function that returns an object.

Here’s an example:


  function createCar(make, model, year) {
    return {
      make: make,
      model: model,
      year: year,
      drive: function() {
        console.log(`Driving the ${this.make} ${this.model}...`);
      }
    };
  }
  

In this example, the createCar function takes three arguments: make, model, and year. It then returns an object that has properties for make, model, and year, as well as a drive method that logs a message to the console.

Step 2: Implementing the Factory Function

To use the factory function, we’ll need to call it and pass in any arguments that it requires.

Here’s an example:


const car1 = createCar('Honda', 'Civic', 2022);
const car2 = createCar('Toyota', 'Corolla', 2022);
  

In this example, we’re calling the createCar function twice, passing in different arguments each time. This will create two separate objects, one for a Honda Civic and one for a Toyota Corolla.

Step 3: Using the Factory Function

Once we’ve created the objects using the factory function, we can use them just like any other object in JavaScript.

Here’s an example:


  car1.drive(); // logs "Driving the Honda Civic..."
  car2.drive(); // logs "Driving the Toyota Corolla..."
  

In this example, we’re calling the drive method on each of the objects created by the factory function. This will log a message to the console indicating that we’re driving the corresponding car.

Pros and Cons of Factory Pattern in Javascript

Pros

  1. Encapsulation: The Factory Pattern encapsulates object creation and allows you to create objects without exposing the creation logic. This helps to keep your code organized and easy to maintain.
  2. Abstraction: The Factory Pattern provides an abstraction layer between the object creation and the client code, making it easy to change the object creation process without affecting the client code.
  3. Flexibility: With the Factory Pattern, you can create objects dynamically at runtime, based on user input or other conditions. This makes it a flexible and versatile pattern for object creation.
  4. Reusability: The Factory Pattern promotes code reusability by providing a centralized place for object creation logic. This reduces code duplication and makes it easier to maintain and modify the code.

Cons

  1. Complexity: The Factory Pattern can add some complexity to your code, especially if you need to create many different types of objects. It can also be difficult to understand and implement for beginners.
  2. Performance: The Factory Pattern can have a negative impact on performance if the factory function is called frequently or if the object creation process is resource-intensive.
  3. Coupling: The Factory Pattern can create tight coupling between the factory and the created objects, which can make it difficult to change the object creation process later.

Singleton Pattern

The Singleton Pattern is a design pattern that restricts the instantiation of a class to a single instance and provides a global point of access to that instance. In JavaScript, you can implement the Singleton Pattern using a simple object literal or a constructor function.

Here’s an example of how to create a Singleton using an object literal:


  const singleton = {
    instance: null,
    getInstance: function() {
      if (!this.instance) {
        this.instance = { 
          // properties and methods of your singleton object
        };
      }
      return this.instance;
    }
  };
  

In this example, we define a singleton object that has an instance property and a getInstance method. The getInstance method checks whether the instance property is null, and if so, it creates a new instance of the object. If the instance property is not null, it simply returns the existing instance.

To use the Singleton, you can call the getInstance method:


  const mySingleton = singleton.getInstance();
  

This will either create a new instance of the object or return the existing instance, depending on whether an instance has already been created.

Here’s an example of how to create a Singleton using a constructor function:


  function MySingleton() {
    if (!MySingleton.instance) {
      MySingleton.instance = this;
      // properties and methods of your singleton object
    }
    return MySingleton.instance;
  }

In this example, we define a MySingleton constructor function that checks whether the instance property is null and creates a new instance of the object if it is. We also set the instance property to the current object using this, and return the instance.

To use the Singleton, you can create a new instance of the MySingleton constructor function:


  const mySingleton = new MySingleton();

This will either create a new instance of the object or return the existing instance, depending on whether an instance has already been created.

The Singleton Pattern offers several advantages, including easy access to a single instance of an object, and control over the instantiation process. However, it can also have some drawbacks, such as tight coupling between the Singleton object and other parts of your code, and difficulty in unit testing. It’s important to weigh the pros and cons of using the Singleton Pattern in your specific use case and to use it judiciously.

Pros and Cons of Singleton Pattern in Javascript

Pros

  1. Easy access to a single instance: The Singleton Pattern provides a global point of access to a single instance of an object, making it easy to access that object from anywhere in your code.
  2. Control over the instantiation process: By restricting the instantiation of a class to a single instance, the Singleton Pattern gives you control over the creation of that object and ensures that only one instance is created.
  3. Conserves resources: By limiting the number of instances of an object, the Singleton Pattern can help conserve resources in your application.
  4. Provides a shared state: Because there is only one instance of the object, it can be used to maintain a shared state across your application.

Cons

  1. Tight coupling: The Singleton Pattern can lead to tight coupling between the Singleton object and other parts of your code. This can make it difficult to change the behavior of your code without also changing the behavior of the Singleton object.
  2. Hard to unit test: Because the Singleton object is global, it can be difficult to unit test your code in isolation. This can make it harder to catch bugs and maintain your code over time.
  3. Can lead to code bloat: Because the Singleton object is global, it can be easy to add too many properties and methods to the object, leading to code bloat and decreased maintainability.
  4. Can lead to unexpected behavior: Because there is only one instance of the object, any changes made to that object will be reflected across your application. This can lead to unexpected behavior and make it harder to reason about your code.

Currying in Javascript

Currying is transformation of a function that translate a function from callable as f(a,b,c) into callable as f(a)(b)(c). Currying doesn’t call a function it just transform it.

In other words we can say that Currying is breaking down function with multiple arguments one into one or more functions that each accept a single argument.


    
    /**
      syntax for Currying
     */
     
     f(a,b,c) => f(a)(b)(c)
    

Simple Example for Multiplying Numbers


    
    /**
      Simple example for multiplying numbers
     */
     
     const multiplyNums = (a, b, c) => a * b * c;
     console.log("MultiplyNums ::", multiplyNums(5, 6, 7));
    

After Applying Currying


    
    /**
      Simple example for multiplying numbers after using Currying
     */
     
     const curriedMultiplyNums = (a) => (b) => (c) => a * b * c;
     console.log("Currying Multiply Nums ::",curriedMultiplyNums(6)(7)(8))

    

Hoisting in Javascript (functions and variables)

Hoisting is the process of putting all functions and variables declaration in the memory during compile phase. Hoisting happened on every execution context.

 JavaScript only hoists declarations, not the initializations.

Important points about Hoisting

  • In Javascript functions are fully hoisted. So functions can be accessed from anywhere.


  /**
     function can called before it's declaration
   */

a()
function a() {
    console.log("Function Declarations .....");
    return 1;
}
a()

  /**
     function can called after it's declaration
   */

Note: Hoisting allows us to call functions before even writing them in our code.

  • var variables are hoisted and initialized with undefined values.

var x=5;
console.log(x);

  /**
     x can be able to access after it's declaration.
   */

  • let and const are also fully hoisted and not initialized with any value.

const y=5;
let z=7;
  /**
     y and z can be able to access after declaration
   */

console.log(y);
console.log(z);
  • If we are going to access a var variable before it’s declaration then it will be undefined.


  /**
     x can't be able to access before declaration if we want to access
     it before then get undefined 
   */

console.log(x);
var x=5;
  • If we are going to access let and const variable before its declaration then it will throw a reference error.


  /**
     y and z can't be able to access before declaration if we want to access
     it before then it will throw reference error 
   */
console.log(y)
console.log(z); const y=5; let z=7;

How to encrypt and decrypt Data using node.js

Encryption and Decryption are basically used for security purposes. We convert our actual data in some other form using some algorithms sha, RSA, etc during encryption. Vice versa we convert our encrypted data into actual forum during decryption.

In Node.js for Encryption and Decryption, we use crypto
package.

During Encryption and, Decryption we use security keys to make our encryption more strong.

For Encryption and, Decryption, we also used term encoding and decoding. During encryption, we encode our data and during decryption, we decode our data. 

Now we will write code for encrypting our data then after we will write code for decrypting our data.

But before that at first, we will declare our security keys that we are using for encryption and decryption.


// Declare package
var crypto = require('crypto');
// Declareing secret_key
let secret_key = 'encrypton_decryption';
// Declare secret_iv
let secret_iv = 'encrypton_decryption_iv';
// Declare encryption method
let encrypt_method = "AES-256-CBC";

Then after we will write code for encrypting our data as shown below.


const encryptData = async function (data) {
  let key = crypto.createHash('sha256').update(secret_key).digest('hex').substr(0, 32);
  let iv = crypto.createHash('sha256').update(secret_iv).digest('hex').substr(0, 16);
  let cipher = crypto.createCipheriv(encrypt_method, key, iv);
  let encrypted = cipher.update(data, 'utf8', 'base64');
  encrypted += cipher.final('base64');
  return Buffer.from(Buffer.from(encrypted).toString('utf8')).toString('base64');
}

For calling this function we write these lines of code


let hw = encryptData("hello");
console.log(hw);

OutPut:
encrypt data
Now for decryption of our data, we will write these lines of code


const decryptData = async function (data) {
  let key = crypto.createHash('sha256', secret_key).update(secret_key).digest('hex').substr(0, 32);
  let iv = crypto.createHash('sha256', secret_key).update(secret_iv).digest('hex').substr(0, 16);
  var decipher = crypto.createDecipheriv(encrypt_method, key, iv);
  var dec = decipher.update(Buffer.from(data, 'base64').toString('ascii'), 'base64', 'utf8');
  dec += decipher.final('utf8');
  return Buffer.from(dec).toString('utf8');
}

And during calling decryptData function we will pass encrypted data that has been obtained from encryptData function as shown below


let decryphw = decryptData('SEJFL0VVYy83SGcwc1prZFZST3A2Zz09');
console.log(decryphw);

OutPut:

Get Latest CSV file from Folder using Node.js

getLatestFile.js



/***
 * Read lestest file property 
 * 
 */

const fs = require('fs')
async function getLatestFile() {
    const dirPath = '/home/dheeraj/Documents/BlogPost/Downloads';
    let dirCont = fs.readdirSync(dirPath);
    let files = dirCont.filter(function (elm) { return elm.match(/.*\.(csv)/ig); });
    for (let fileP = 0; fileP < files.length; fileP++) {
        let filsStats = fs.statSync(dirPath + "/" + files[fileP]);
        if (new Date(filsStats['birthtime']).getDate() === new Date().getDate() &&
            new Date(filsStats['birthtime']).getMonth() === new Date().getMonth() &&
            new Date(filsStats['birthtime']).getFullYear() === new Date().getFullYear() &&
            new Date(filsStats['birthtime']).getHours() === new Date().getHours() //&& 
        ) {
            return {
                fileName: files[fileP],
                fileLocation: dirPath + "/" + files[fileP]
            };
        }
    }
    return {
        fileName: 'orderFailed.png',
        fileLocation: dirPath + "/" + 'orderFailed.png'
    };
}

Generate test case
getLatestFile.test.js


const {getLatestFile} = require('./getLatestFile')

async function getLatest (){
    let latest = await getLatestFile();
     console.log(latest);
}

getLatest();

OutPut:

Download Code From git Repo

Regex with JavaScript Part 3

Match WhiteSpaces

During searching or matching a string. We come across a situation where we need to match spaces in String literals.

For matching spaces in String literals, we use \s  which is a lowercase s.

Example:



/**
* Checking for WhiteSpaces
*/

let checkForWhiteSpaces = "Remove WhiteSpaces from everywhere";
let spaceRegex=/\s/g;
console.log(checkForWhiteSpaces.match(spaceRegex));

OutPut:

Match Non-Whitespace Characters

Previously we had seen for searching white spaces using /s which lowercase s.

Here we are looking for searching Non-Whitespace and that can be done using /S , yes using upperCase s.

Example:



/**
 * Checking for WhiteSpaces
 */

 let checkForWhiteSpaces = "Remove WhiteSpaces from everywhere";
 let spaceRegex=/\s/g;
 console.log(checkForWhiteSpaces.match(spaceRegex));

OutPut:

Specify Upper and Lower Number of Matches

We can specify the lower and upper number of patterns with quantity specifiers.

Quantity specifiers are used within curly brackets ({ and }).

Example:



/**
 * specify upper and lower number of match
 */

let myString ="mmmmmmmk";
let mySecondString ="mk";
// match word "mmmmmmmk" only it has minimum 2 and maximum 4 'm'
let myRegex=/m{2,4}k/;
console.log(myRegex.test(myString));
console.log(myRegex.test(mySecondString));

OutPut:

Specify Only the Lower Number of Matches
Passed

Sometimes we need to match only a lower number of matches.

So To specify a lower number of matches keep the lower number of matches followed by comma in curly bracket ( { n, } ).

where n is a lower number.

Example:



/**
* specify lower number of match
*/

let myString ="pinnnnnnnnnnk";
let mySecondString ="pinnk";
// match word "pinnk" only it has four or more letter of n
let myRegex=/pin{4,}k/;
console.log(myRegex.test(myString));
console.log(myRegex.test((mySecondString)));

OutPut:

Specify Exact Number of Matches

Sometimes we need to specify an exact number of matches.

To specify an exact number of pattern just add that number in curly bracket.

Example:


/**
* specify exact match
*
*/

let myString = "apple";
let mySecondString ="aple";
//p should be appear two times
let myRegex = /ap{2}l/;
console.log(myRegex.test(myString));
console.log(myRegex.test(mySecondString));

OutPut:

Check for All or None

Sometimes we are not sure about the pattern that we are searching for. 

In that case, we use ‘?’ i.e question mark which check for zero or one of the preceding element.

In other words, we can also say that the previous character is optional i.e if that exists then fine and if not then also no problem.

Example:



/**
*
* Check for All or None
*/


let american ="favorite";
let british ="favourite";
let regexPattern = /favou?rite/;

//In this example 'u' is optional
console.log(regexPattern.test(american));
console.log(regexPattern.test(british));

OutPut:

Positive and Negative Lookahead

Lookaheads are patterns in Javascript that tells to Javascript to look-ahead in your string to check for pattern further long.

It can be helpful during searching multiple patterns on the same string.

There are two kinds of Lookaheads :

  • Positive lookahead
  • Negative lookahead

Positive lookahead :

– Look to make sure the element in the search pattern is there, but won’t actually match it.

– Positive Lookahead is used as (?= …)

– Where  the ... is the required part that is not matched.

Negative lookahead :

– Look to make sure the element in the search pattern is not there.

– Negative lookahead is used as (?!...) 

– where the ... is the pattern that you do not want to be there.

Example:



/**
 * lookahead 
 * 
 */

 let myPassword = "ohMyGod123";
 let mySecondPassword ="ohmyGod";
 // regex for a string greater than 5 character long and don't begin with number and have two consequitive numbers
 let myRegex = /^(?=\w{6}(?=\D+\d{2}))/;
 console.log(myRegex.test(myPassword));
 console.log(myRegex.test(mySecondPassword));

OutPut:

Check For Mixed Grouping of Characters Passed

Sometimes we need to match a group of Characters using regular expression.
We can achieve that using () i.e parenthesis.

Example :



/**
*  Mixed grouping Characters
*/

let myString = "laptop";
// check for multiple group of characters
let myRegex = /(lap|Desk)top/;
console.log(myRegex.test(myString));

OutPut:

Reuse Patterns Using Capture Groups

Some patterns are multiple times in a string. Then it is wastage of time to write the pattern multiple times for searching in a string.

Example:



/**
* Reuse patterns using capture Groups
*
*/

let myString ="mummy mummy mummy";
let myRegex = /(\w+)\s\1/;

console.log(myRegex.test(myString));

console.log(myString.match(myRegex));

OutPut:

Use Capture Groups to Search and Replace

We can search and after that replace in string using .replace().

.replace() contains two parameters :

  • First parameter the string that we are searching for
  • Second parameter the string from which we want to replace.

Example:



/**
* Capture group for search andd replace
*/

let myString= "Baba Black Sheep";
// replace Baba Black sheep with Sheep Black Baba
let myRegex = /(\w+)\s(\w+)\s(\w+)/
let myReplacementString= '$3 $2 $1';
console.log(myString.replace(myRegex,myReplacementString));

OutPut:

Remove Whitespace from Start and End

Sometimes we come across the problem that some string contains unwanted whitespaces and that we need to remove these whitespaces from our string.
For removing start and end whitespaces from a string from we use .trim()
method.

Example:



/***
* removing whitespace from string using .trim()
*/

let hello = "   Hello, World!  ";

let result = hello.trim();
console.log(result);

OutPut:

Regex with Javascript Part 2

In the previous post, we have started Regex with JavaScript and discussed some important points of Regex in JavaScript.

In today’s post, we are going to continue with the same topic.

Match Single Character with multiple possibilities

In the previous, we have discussed match pattern where we had dealt with a string pattern (/string/) and wildcard both (/./) and both have its own significance.

Where one finds the exact match and one works with everything.
We can also enhance this search using Character classes.
Character classes allows us to define a group of characters after placing them in square bracket ([ ]).

Example:



/**
 *  range number
 */


 let emailString = "krdheeraj51@gmail.com";
 let regexString = /[a-z@0-9]/g;
 console.log(emailString.match(regexString));

OutPut:

Match letters of Alphabet

In the case of Character match pattern, we can also define a range.
Suppose we have taken all characters from are then we can define our character classes like [a-e];

Example:



/**
* Character classes
*/

let catStr = "cat";
let batStr = "bat";
let ratStr = "rat";
let bgRegex = /[a-e]at/;

console.log(catStr.match(bgRegex));
console.log(batStr.match(bgRegex));
console.log(ratStr.match(bgRegex));

OutPut:

Match Numbers and letters of Alphabet

( – ) is not limited to matching range of character as we have seen previously. But it will also work to match a range of numbers.
For matching a number in between 10 to 15 we can write down like [ 10-15 ].

Example:



/**
*  range number
*/

let emailString = "krdheeraj51@gmail.com";
let regexString = /[a-z@0-9]/g;
console.log(emailString.match(regexString));

OutPut:

Match Single Characters not specified

Till now we have created a set of characters that we want to match.
We can also create a set of characters that we don’t want to match and these types of character sets are known as negated character set.

For using the negated character set we have to use caret character ( ^ ).

Example :

previous post

/**
* Ignore 0 to 9 and all vowel character
*
**/previous post

let quoteSample ="4th Umpire";
//create a regex for Ignore 0 to 9 and all vowel character
let myRegex = /[^0-9^aeiou]/gi;
console.log(quoteSample.match(myRegex));

OutPut:

Match Character that Occurs one or more time

Some times we need to match a group of Character that appears one or more than once.

We can check this case using + character. 

Remember::  In this case Character should be repeated consequently.

It means Character is being repeated one after another.

previous post suppose our String is “abc” and we are using our regex /a+/g then it will return [“a”].

But if our String is like “aabc” then it will return [“a”,”a”].

Example :



/**
* Handle case of matching zero or more Character
*/


let myString = "fuuuuuuuuuuun!!";
let realString = "It is funny time."
let moreString = "Not Interested.";

let myRegex = /fu*/i;

console.log(myString.match(myRegex));
console.log(realString.match(myRegex));
console.log(moreString.match(myRegex));

OutPut:

Match Characters that Occur Zero or More Times

The previous scenario handled the situation of occurring a Character one or more times.
At this time we will handle the same case of occurring a Character that may be occurred zero or more times.
Fo that that purpose we will use * Character.

Example:



/**
* Handle case of matching zero or more Character
*/

let myString = "fuuuuuuuuuuun!!";
let realString = "It is funny time."
let moreString = "Not Interested.";

let myRegex = /fu*/i;

console.log(myString.match(myRegex));
console.log(realString.match(myRegex));
console.log(moreString.match(myRegex));

OutPut:

 

More Post on Regex

Regex with Javascript

 

Regex with Javascript

Regex stands for Regular Expressions also known as Regexp are special strings that represent a search pattern.

For programmers, Regex is like pills that make our task easy.

Regex contains special meaning for some characters that we will explain in further discussion during this post.

Now we will perform some action using functions of Regular Expression.

Match String Using test() method :

As we know that Regex is used to match parts of string.
So, if we want to find “foodie” in the string “Tommy is a foodie.” then we have to use /foodie/ as expression.

Now /foodie/ is our Regex.

Note: Quote marks are not required within regular expression.

JavaScript has multiple ways to use Regex. One of the ways is to use test() method which returns true or false.

Syntax :



regex.test(string)
//return true or false

Example :



var myString = "Codeteaser";
//if our search pattern is teaser from above String
var myRegex = /teaser/;
console.log(myRegex.test(myString));

OutPut:

Match String Literals

We can follow the same approach with String Literals as we have followed previously for matching a string pattern form a strong. In this case, I am taking the same example which I had discussed at the beginning of the post.

Example :


var myStringLterals = "Tommy is a foodie.";
//Search for foodie from string literal
var myRegex =/foodie/;
console.log(myRegex.test(myStringLterals));

OutPut:

But from this approach another form of foodie like Foodie, FOODIE will not match.

Example :


var myStringLterals = "Tommy is a foodie.";
//Search for foodie from string literal
var myRegex =/Foodie/;
console.log(myRegex.test(myStringLterals));

OutPut:

Searching Multiple Option at a time

If we have a string literal “Ronny has a pet cat.” and we are not sure about pet name i.e it is cat or dog or whatever it is. But if we have to add as search pattern on this specific string literal then, in this case, we can follow this approach as shown below.

Example :


var myStringLiteral ="Ronny has a pet cat."
// search for pet name but not sure about pet name
var myRegex = /dog|cat/
console.log(myRegex.test(myStringLiteral));

OutPut:

Note :

We can search multiple patterns using OR or | operator.

Ignore Cases while matching

During matching pattern in a string literal, we had faced a problem while match pattern remains in different cases i.e upperCase (“A”, ”B”, “C” … “Z”) or lowerCases (“a”,”b”,”c” … “z”).
As we had discussed foodie, Foodie or FOODIE are different patterns and these dissimilarities are due to letter case differences.

So, we can ignore letter cases in pattern match using flags in Regex. There are various flags in Regex and ignoring case we will use i flag.

Example:


var myStringLterals = "Tommy is a foodie.";
//Search for foodie from string literal using i flag
var myRegex =/Foodie/i;
console.log(myRegex.test(myStringLterals));

OutPut:

Extract Matches

So till now, we have worked on pattern is existing or not in a String or String Literal. Now we going to extract match pattern from string.
For that purpose, we have to use .match() method.

Example:



/**
* Extrat match pattern
*/

var myExtractStringLiteral="Selena Gomez is a pop Singer.";
// Looking for match pattern
var myRegex =/Singer/;
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

Find more than first

match() method returns the first pattern from a string or string literal.

Example:



/**
* only find first pattern
*/

var myExtractStringLiteral = "Jonny Jonny yes papa";
// Looking for string pattern from a string literal
var myRegex =/Jonny/;
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

But if a string Literal contains multiple times the same pattern then in that case for returning all string pattern we use the g flag as shown in the upcoming example.

Example:



/**
* return all match pattern from a string literal 
*/

var myExtractStringLiteral = "Jonny Jonny yes papa";
// Looking for all match pattern inside String Literal
var myRegex =/Jonny/g;
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

Match anything with wildCard period

Sometimes we don’t know the exact pattern that we want to match. So, in that case, we have to try all possible words that we think for a matching pattern.
And i.e seriously a tough task.
But Regex contains wildCard character: . (dot)
The wildCard character will match anyone character of string.
The wildcard is also called a dot or period.
For example, if we have to match “hug”, “huh”, “hut” then our Regex pattern would be /hu./

Example:



/**
* wildCrad
*/


var myExtractStringLiteral = "I don't like fun during my working period.";
// Searching for fun
var myRegex =/fu./;
//After using dot it will match one character
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

Note: We will discuss more about Regex in further posts.