0% found this document useful (0 votes)
88 views37 pages

MEAN (Unit 2)

The document provides an overview of MEAN Stack technologies, focusing on JavaScript fundamentals including objects, arrays, functions, and control statements. It explains how to create and manipulate objects and arrays, as well as various JavaScript operators and control structures. Additionally, it covers AngularJS expressions and single-page application development using AngularJS.

Uploaded by

diyadivya528
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views37 pages

MEAN (Unit 2)

The document provides an overview of MEAN Stack technologies, focusing on JavaScript fundamentals including objects, arrays, functions, and control statements. It explains how to create and manipulate objects and arrays, as well as various JavaScript operators and control structures. Additionally, it covers AngularJS expressions and single-page application development using AngularJS.

Uploaded by

diyadivya528
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

MEAN Stack Technologies

UNIT II: JavaScript: The Basic of JavaScript: Objects, Primitives Operations and
Expressions, Control Statements, Arrays, Functions, Constructors, Pattern Matching using
Regular Expressions.
Angular Java Script Angular JS Expressions: ARRAY, Objects, $eval, Strings, Angular JS
Form Validation & Form Submission, Single Page Application development using Angular
JS

Objects in Javascript
An object in JavaScript is a data structure used to store related data
collections. It stores data as key-value pairs, where each key is a unique
identifier for the associated value. Objects are dynamic, which means the
properties can be added, modified, or deleted at runtime.
There are two primary ways to create an object in JavaScript: Object
Literal and Object Constructor.
1. Creation Using Object Literal
The object literal syntax allows you to define and initialize an object with
curly braces {}, setting properties as key-value pairs.

let obj = {
name: "Sourav",
age: 23,
job: "Developer"
};
console.log(obj);

Output
{ name: 'Sourav', age: 23, job: 'Developer' }

2. Creation Using new Object() Constructor

let obj = new Object();


obj.name= "Sourav",
obj.age= 23,
obj.job= "Developer"

console.log(obj);

Output
{ name: 'Sourav', age: 23, job: 'Developer' }
Basic Operations on JavaScript Objects
1. Accessing Object Properties
You can access an object’s properties using either dot
notation or bracket notation

let obj = { name: "Sourav", age: 23 };

// Using Dot Notation


console.log(obj.name);

// Using Bracket Notation


console.log(obj["age"]);

Output
Sourav
23

2. Modifying Object Properties


Properties in an object can be modified by reassigning their values.

let obj = { name: "Sourav", age: 22 };


console.log(obj);

obj.age = 23;
console.log(obj);

Output
{ name: 'Sourav', age: 22 }
{ name: 'Sourav', age: 23 }

3. Adding Properties to an Object


You can dynamically add new properties to an object using dot or bracket
notation.

let obj = { model: "Tesla" };


obj.color = "Red";
console.log(obj);

Output
{ model: 'Tesla', color: 'Red' }

4. Removing Properties from an Object


The delete operator removes properties from an object.

let obj = { model: "Tesla", color: "Red" };


delete obj.color;

console.log(obj);

Output
{ model: 'Tesla' }

5. Checking if a Property Exists


You can check if an object has a property using the in operator
or hasOwnProperty() method.

let obj = { model: "Tesla" };


console.log("color" in obj);
console.log(obj.hasOwnProperty("model"));

Output
false
true

6. Iterating Through Object Properties


Use for...in loop to iterate through the properties of an object.

let obj = { name: "Sourav", age: 23 };


for (let key in obj) {
console.log(key + ": " + obj[key]);
}

Output
name: Sourav
age: 23

7. Merging Objects
Objects can be merged using Object.assign() or the spread syntax
{ ...obj1, ...obj2 }.

let obj1 = { name: "Sourav" };


let obj2 = { age: 23};

let obj3 = { ...obj1, ...obj2 };


console.log(obj3);

Output
{ name: 'Sourav', age: 23 }

8. Object Length
You can find the number of properties in an object using Object.keys().

let obj = { name: "Sourav", age: 23 };


console.log(Object.keys(obj).length);

Output
2

JavaScript Operators
JavaScript operators are symbols or keywords used to perform operations
on values and variables. They are the building blocks of JavaScript
expressions and can manipulate data in various ways.

1. JavaScript Arithmetic Operators


Arithmetic Operators perform mathematical calculations like addition,
subtraction, multiplication, etc.

const sum = 5 + 3; // Addition


const diff = 10 - 2; // Subtraction
const p = 4 * 2; // Multiplication
const q = 8 / 2; // Division
console.log(sum, diff, p, q);

Output
8 8 8 4
 + adds two numbers.
 - subtracts the second number from the first.
 * multiplies two numbers.
 / divides the first number by the second.
2. JavaScript Assignment Operators
Assignment operators are used to assign values to variables. They can
also perform operations like addition or multiplication before assigning the
value.

let n = 10;
n += 5;
n *= 2;
console.log(n);

Output
30
 = assigns a value to a variable.
 += adds and assigns the result to the variable.
 *= multiplies and assigns the result to the variable.
3. JavaScript Comparison Operators
Comparison operators compare two values and return a boolean (true or
false). They are useful for making decisions in conditional statements.

console.log(10 > 5);


console.log(10 === "10");

Output
true
false
 > checks if the left value is greater than the right.
 === checks for strict equality (both type and value).
 Other operators include <, <=, >=, and !==.
4. JavaScript Logical Operators
Comparison operators are mainly used to perform the logical operations
that determine the equality or difference between the values.

const a = true, b = false;


console.log(a && b); // Logical AND
console.log(a || b); // Logical OR

Output
false
true
 && returns true if both operands are true.
 || returns true if at least one operand is true.
 ! negates the boolean value.
5. JavaScript Bitwise Operators
Bitwise operators perform operations on binary representations of
numbers.

const res = 5 & 1; // Bitwise AND


console.log(res);

Output
1
 & performs a bitwise AND.
 | performs a bitwise OR.
 ^ performs a bitwise XOR.
 ~ performs a bitwise NOT.
6. JavaScript Ternary Operator
The ternary operator is a shorthand for conditional statements. It takes
three operands.

const age = 18;


const status = age >= 18 ? "Adult" : "Minor";
console.log(status);

Output
Adult
condition ? expression1 : expression2 evaluates expression1 if the
condition is true, otherwise evaluates expression2.
7. JavaScript Comma Operator
Comma Operator (,) mainly evaluates its operands from left to right
sequentially and returns the value of the rightmost operand.

let n1, n2
const res = (n1 = 1, n2 = 2, n1 + n2);
console.log(res);

Output
3
 Each expression is evaluated from left to right.
 The final result of the expression is the rightmost value.
8. JavaScript Unary Operators
Unary operators operate on a single operand (e.g., increment,
decrement).

let x = 5;
console.log(++x); // Pre-increment
console.log(x--); // Post-decrement (Output: 6, then x becomes 5)

Output
6
6
 ++ increments the value by 1.
 -- decrements the value by 1.
 typeof returns the type of a variable.
9. JavaScript Relational Operators
JavaScript Relational operators are used to compare its operands and
determine the relationship between them. They return a Boolean value
(true or false) based on the comparison result.

const obj = { length: 10 };


console.log("length" in obj);
console.log([] instanceof Array);

Output
true
true
 in checks if a property exists in an object.
 instanceof checks if an object is an instance of a constructor.
10. JavaScript BigInt Operators
BigInt operators allow calculations with numbers beyond the safe integer
range.

const big1 = 123456789012345678901234567890n;


const big2 = 987654321098765432109876543210n;
console.log(big1 + big2);

Output
1111111110111111111011111111100n
 Operations like addition, subtraction, and multiplication work with
BigInt.
 Use n suffix to denote BigInt literals.
11. JavaScript String Operators
JavaScript String Operators include concatenation (+) and concatenation
assignment (+=), used to join strings or combine strings with other data
types.

const s = "Hello" + " " + "World";


console.log(s);

Output
Hello World
 + concatenates strings.
 += appends to an existing string.
12. JavaScript Chaining Operator (?.)
The optional chaining operator allows safe access to deeply nested
properties without throwing errors if the property doesn’t exist.
const obj = { name: "Aman", address: { city: "Delhi" } };
console.log(obj.address?.city);
console.log(obj.contact?.phone);

Output
Delhi
undefined
 ?. safely accesses a property or method.
 Returns undefined if the property doesn’t exist.
Control Statements in JavaScript
JavaScript control statement is used to control the execution of a
program based on a specific condition. If the condition meets then a
particular block of action will be executed otherwise it will execute another
block of action that satisfies that particular condition.
Types of Control Statements in JavaScript
 Conditional Statement: These statements are used for decision-
making, a decision
 n is made by the conditional statement based on an expression that is
passed. Either YES or NO.
 Iterative Statement: This is a statement that iterates repeatedly until a
condition is met. Simply said, if we have an expression, the statement
will keep repeating itself until and unless it is satisfied.
There are several methods that can be used to perform control statements
in JavaScript:
Table of Content
 If Statement
 Using If-Else Statement
 Using Switch Statement
 Using the Ternary Operator (Conditional Operator)
 Using For loop
Approach 1: If Statement
In this approach, we are using an if statement to check a specific
condition, the code block gets executed when the given condition is
satisfied.
Syntax:
if ( condition_is_given_here ) {
// If the condition is met,
//the code will get executed.
}
Example: In this example, we are using an if statement to check our
given condition.

const num = 5;

if (num > 0) {
console.log("The number is positive.");
};

Output
The number is positive.
Approach 2: Using If-Else Statement
The if-else statement will perform some action for a specific condition. If
the condition meets then a particular code of action will be executed
otherwise it will execute another code of action that satisfies that particular
condition.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Example: In this example, we are using the if..else statement to verify
whether the given number is positive or negative.

let num = -10;

if (num > 0)
console.log("The number is positive.");
else
console.log("The number is negative");

Output
The number is negative
Approach 3: Using Switch Statement
The switch case statement in JavaScript is also used for decision-making
purposes. In some cases, using the switch case statement is seen to be
more convenient than if-else statements.
Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example: In this example, we are using the above-explained approach.

let num = 5;

switch (num) {
case 0:
console.log("Number is zero.");
break;
case 1:
console.log("Nuber is one.");
break;
case 2:
console.log("Number is two.");
break;
default:
console.log("Number is greater than 2.");
};

Output
Number is greater than 2.
Approach 4: Using the Ternary Operator (Conditional Operator)
The conditional operator, also referred to as the ternary operator (?:), is a
shortcut for expressing conditional statements in JavaScript.
Syntax:
condition ? value if true : value if false
Example: In this example, we are using the ternary operator to find
whether the given number is positive or negative.
let num = 10;

let result = num >= 0 ? "Positive" : "Negative";

console.log(`The number is ${result}.`);

Output
The number is Positive.
Approach 5: Using For loop
In this approach, we are using for loop in which the execution of a set of
instructions repeatedly until some condition evaluates and becomes false
Syntax:
for (statement 1; statement 2; statement 3) {
// Code here . . .
}
Example: In this example, we are using Iterative Statement as a for loop,
in which we find the even number between 0 to 10.

for (let i = 0; i <= 10; i++) {


if (i % 2 === 0) {
console.log(i);
}
};

Output
0
2
4
6
8
10

JavaScript Arrays
In JavaScript, an array is an ordered list of values. Each value is called an
element, and each element has a numeric position in the array, known as
its index. Arrays in JavaScript are zero-indexed, meaning the first element
is at index 0, the second at index 1, and so on.

Array in JavaScript
1. Create Array using Literal
Creating an array using array literal involves using square brackets [] to
define and initialize the array.

// Creating an Empty Array


let a = [];
console.log(a);

// Creating an Array and Initializing with Values


let b = [10, 20, 30];
console.log(b);

Output
[]
[ 10, 20, 30 ]
2. Create using new Keyword (Constructor)
The "Array Constructor" refers to a method of creating arrays by
invoking the Array constructor function.

// Creating and Initializing an array with values


let a = new Array(10, 20, 30);

console.log(a);

Output
[ 10, 20, 30 ]
Note: Both the above methods do exactly the same. Use the array literal
method for efficiency, readability, and speed.
Recommended Links
 Insert Elements in a JS array
 Delete Elements from a JS Array
 Interesting Facts about JavaScript Arrays
 JavaScript Array Reference
 JavaScript Array Examples
 Cheat Sheet-A Basic guide to JavaScript .
Basic Operations on JavaScript Arrays
1. Accessing Elements of an Array
Any element in the array can be accessed using the index number. The
index in the arrays starts with 0.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Accessing Array Elements


console.log(a[0]);
console.log(a[1]);

Output
HTML
CSS

2. Accessing the First Element of an Array


The array indexing starts from 0, so we can access first element of array
using the index number.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];

// Accessing First Array Elements


let fst = a[0];

console.log("First Item: ", fst);

Output
First Item: HTML

3. Accessing the Last Element of an Array


We can access the last array element using [array.length - 1] index
number.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Accessing Last Array Elements


let lst = a[a.length - 1];

console.log("First Item: ", lst);

Output
First Item: JS

4. Modifying the Array Elements


Elements in an array can be modified by assigning a new value to their
corresponding index.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];
console.log(a);

a[1]= "Bootstrap";
console.log(a);

Output
[ 'HTML', 'CSS', 'JS' ]
[ 'HTML', 'Bootstrap', 'JS' ]

5. Adding Elements to the Array


Elements can be added to the array using methods
like push() and unshift().
 The push() method add the element to the end of the array.
 The unshift() method add the element to the starting of the array.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Add Element to the end of Array


a.push("Node.js");

// Add Element to the beginning


a.unshift("Web Development");

console.log(a);

Output
[ 'Web Development', 'HTML', 'CSS', 'JS', 'Node.js' ]

6. Removing Elements from an Array


To remove the elements from an array we have different methods
like pop(), shift(), or splice().
 The pop() method removes an element from the last index of the array.
 The shift() method removes the element from the first index of the
array.
 The splice() method removes or replaces the element from the array.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];
console.log("Original Array: " + a);

// Removes and returns the last element


let lst = a.pop();
console.log("After Removing the last: " + a);

// Removes and returns the first element


let fst = a.shift();
console.log("After Removing the First: " + a);

// Removes 2 elements starting from index 1


a.splice(1, 2);
console.log("After Removing 2 elements starting from index 1: " + a);

Output
Original Array: HTML,CSS,JS
After Removing the last: HTML,CSS
After Removing the First: CSS
After Removing 2 elements starting from index 1: CSS

7. Array Length
We can get the length of the array using the array length property.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

let len = a.length;

console.log("Array Length: " + len);

Output
Array Length: 3

8. Increase and Decrease the Array Length


We can increase and decrease the array length using the JavaScript
length property.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"]

// Increase the array length to 7


a.length = 7;

console.log("After Increasing Length: ", a);

// Decrease the array length to 2


a.length = 2;
console.log("After Decreasing Length: ", a)
Output
After Increasing Length: [ 'HTML', 'CSS', 'JS', <4 empty
items> ]
After Decreasing Length: [ 'HTML', 'CSS' ]

9. Iterating Through Array Elements


We can iterate array and access array elements using for loop and
forEach loop.
Example: It is an example of for loop.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Iterating through for loop


for (let i = 0; i < a.length; i++) {
console.log(a[i])
}

Output
HTML
CSS
JS
Example: It is the example of Array.forEach() loop.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Iterating through forEach loop


a.forEach(function myfunc(x) {
console.log(x);
});

Output
HTML
CSS
JS
10. Array Concatenation
Combine two or more arrays using the concat() method. It returns new
array containing joined arrays elements.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS", "React"];
let b = ["Node.js", "Expess.js"];

// Concatenate both arrays


let concateArray = a.concat(b);

console.log("Concatenated Array: ", concateArray);

Output
Concatenated Array: [ 'HTML', 'CSS', 'JS', 'React',
'Node.js', 'Expess.js' ]

11. Conversion of an Array to String


We have a builtin method toString() to converts an array to a string.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Convert array ot String


console.log(a.toString());

Output
HTML,CSS,JS

12. Check the Type of an Arrays


The JavaScript typeof operator is used ot check the type of an array. It
returns "object" for arrays.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Check type of array


console.log(typeof a);
Output
object
Recognizing a JavaScript Array
There are two methods by which we can recognize a JavaScript array:
 By using Array.isArray() method
 By using instanceof method
Below is an example showing both approaches:

const courses = ["HTML", "CSS", "Javascript"];


console.log("Using Array.isArray() method: ", Array.isArray(courses))
console.log("Using instanceof method: ", courses instanceof Array)

Output
Using Array.isArray() method: true
Using instanceof method: true
Note: A common error is faced while writing the arrays:
const a = [5]
// and
const a = new Array(5)
The above two statements are not the same.
Output: This statement creates an array with an element " [5] ". Try with
the following examples

// Example 1
const a1 = [5]
console.log(a1)

// Example 2
const a2 = new Array(5)
console.log(a2)

Output
[ 5 ]
[ <5 empty items> ]

Functions in JavaScript
Functions in JavaScript are reusable blocks of code designed to perform
specific tasks. They allow you to organize, reuse, and modularize code. It
can take inputs, perform actions, and return outputs.

function sum(x, y) {
return x + y;
}
console.log(sum(6, 9));

Output
15
Function Syntax and Working
A function definition is sometimes also termed a function declaration or
function statement. Below are the rules for creating a function in
JavaScript:
 Begin with the keyword function followed by,
 A user-defined function name (In the above example, the name
is sum)
 A list of parameters enclosed within parentheses and separated by
commas (In the above example, parameters are x and y)
 A list of statements composing the body of the function enclosed within
curly braces {} (In the above example, the statement is "return x + y").
Return Statement
In some situations, we want to return some values from a function after
performing some operations. In such cases, we make use of the return.
This is an optional statement. In the above function, "sum()" returns the
sum of two as a result.
Function Parameters
Parameters are input passed to a function. In the above example, sum()
takes two parameters, x and y.
Calling Functions
After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by
the value of parameters enclosed between the parenthesis.

// Function Definition
function welcomeMsg(name) {
return ("Hello " + name + " welcome to GeeksforGeeks");
}
let nameVal = "User";

// calling the function


console.log(welcomeMsg(nameVal));

Output
Hello User welcome to GeeksforGeeks
Why Functions?
 Functions can be used multiple times, reducing redundancy.
 Break down complex problems into manageable pieces.
 Manage complexity by hiding implementation details.
 Can call themselves to solve problems recursively.
Advantages of Functions in JavaScript
 Reusability: Write code once and use it multiple times.
 Modularity: Break complex problems into smaller, manageable pieces.
 Improved Readability: Functions make code easier to understand.
 Maintainability: Changes can be made in one place without affecting
the entire codebase.
JavaScript Object Constructors
An object is the collection of related data or functionality in the form
of key. These functionalities usually consist of several functions and
variables. All JavaScript values are objects except primitives.
const GFG = {
subject : "programming",
language : "JavaScript",
}
Here, subject and language are
the keys and programming and JavaScript are the values.
Object Constructor
A constructor function is a special type of function in JavaScript that is
used to create and initialize objects. Constructors are used with the new
keyword to create instances of a particular type (object). By using
constructors, we can easily create multiple instances of the same type of
object, all with their own unique properties and methods.


function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log(`My name is ${this.name} and I am ${this.age} years
old.`);
};
}

Output
My name is Akash and I am 30 years old.
My name is Anvesh and I am 25 years old.

this keyword
The this keyword refers to the object it belongs to, like OOPs languages
C++, C#, JAVA etc. this keyword is used in different ways in different
areas. While executing a function in JavaScript that has a reference to its
current execution context, that is the reference by which the function or
data member is called. See the previous example.
Adding Property to an Object
The property can be added to the object by using dot(.) operator
or square bracket.,
const GFG = {
articles: 'computer science',
quantity: 3000,
};
The GFG has two properties "articles" and "quantity". Now we wish to add
one more property name called subject.
Using dot (.) operator
GFG.subject: 'JavaScript';
Using square bracket:
GFG['subject']: 'JavaScript';
Here, subject is the property and 'JavaScript' is the value of the
property. Adding a property to Constructor: We cannot add a property
to an existing constructor like adding a property to an object (see previous
point), for adding a property we need to declare under the constructor.
function GFG(a, b, c) {
this.A = a;
this.B = b;
this.C = c;
this.G = "GEEK";
}
Here, we add a property name G with value "GEEK", in this case the
value "GEEK" is not passed as an argument.
Adding a Method to an Object
We can add a new method to an existing object.
GFG.n = function () {
return this.A + this.B;
};
Here, the object is GFG.
Adding a Method to Constructor
function GFG(a, b, c) {
this.A = a;
this.B = b;
this.C = c;
this.n = function () {
return this.A + this.B;
}
}
Here, in the last line a method is added to an object.
Instantiating an object constructor
There are two ways to instantiate object constructor,
const object_name = new Object(); // or
const object_name = new Object("java", "JavaScript", "C#");

const object_name = { };
In 1st method, the object is created by using new keyword like normal
OOP languages, and "Java", "JavaScript", "C#" are the arguments, that
are passed when the constructor is invoked. In 2nd method, the object is
created by using curly braces "{ }".
Assigning properties to the objects: There are two ways to assigning
properties to the objects.
 Using dot (.) operator:
object_name . properties = value;
 Using third bracket:
object_name [ 'properties'] = value;
Example 1: Object creation by using new keyword and assigning
properties to the object using dot(.) operator.

let gfg = new Object();

gfg.a = "JavaScript";
gfg.b = "GeeksforGeeks";

Output
Subject: JavaScript
Author: GeeksforGeeks
Example 2: Object creation using curly braces and assigning properties
to the object using third bracket "[]" operator.
let gfg = { };

gfg['a'] = "JavaScript";
gfg['b']= "GeeksforGeeks";

Output
Subject: JavaScript
Author: GeeksforGeeks
Example 3: This example shows how to use function() with object
constructor.

let gfg = new Object();

gfg.a = "JavaScript";
gfg.b = "GeeksforGeeks";
gfg.c = function () {
return (gfg.a +" "+ gfg.b);
};

Output
Subject: JavaScript
Author: GeeksforGeeks
Adding the strings: JavaScript GeeksforGeeks
Example 4: Another way to create a function using function name.

let gfg = { };

gfg.a = "JavaScript";
gfg.b = "GeeksforGeeks";
gfg.c = add;
// Declare function add()
function add() {
return (gfg.a +" "+ gfg.b);
};

Output
Subject: JavaScript
Author: GeeksforGeeks
Adding the strings: JavaScript GeeksforGeeks

JavaScript RegExp (Regular Expression)


A regular expression is a special sequence of characters that defines a
search pattern, typically used for pattern matching within text. It's often
used for tasks such as validating email addresses, phone numbers, or
checking if a string contains certain patterns (like dates, specific words,
etc.).
In JavaScript, RegExp is an object that is used to create regular
expressions, which are patterns used to match character combinations in
strings.

// The /i flag makes the pattern case-insensitive


const patt = /Geeks/i;
const s1 = "geeksforgeeks";
const s2 = "forgeeks";

console.log(patt.test(s1));
console.log(patt.test(s2));

Output
true
true
Creating a RegExp in JavaScript
There are two primary ways to create a RegExp in JavaScript
1. Using the RegExp Constructor
The RegExp constructor is useful when you need to create a regular
expression dynamically, such as when the pattern or flags might change
based on user input or other conditions.
let pattern = "hello"; // Pattern to match
let flags = "i"; // Case-insensitive flag
let regex = new RegExp(pattern, flags);

let s = "Hello world";

console.log(regex.test(s));

Output
true
 Here, we dynamically create a RegExp object using the RegExp()
constructor.
 The pattern "hello" will match the string "Hello" because of the 'i' flag,
which makes the search case-insensitive.
 regex.test(s) returns true because "Hello" matches the pattern "hello" in
a case-insensitive manner.
2. Using Regular Expression Literal
This is the most common and simple way to create a regular expression in
JavaScript. It’s especially useful when the pattern is static (doesn’t change
dynamically).

let regex = /hello/i;

let s = "Hello world";

console.log(regex.test(s));

Output
true
 In this example, we define the regular expression directly using literal
notation.
 /hello/i means we're looking for the word "hello", and the 'i' flag
ensures the search is case-insensitive.
 regex.test(s) returns true because "Hello" matches the pattern "hello"
case-insensitively.
Regular Expression Modifiers can be used to perform multiline
searches which can also be set to case-insensitive matching:
Expressions Descriptions

g Find the character globally

i Find a character with case-insensitive matching

m Find multiline matching

Regular Expression Brackets can Find characters in a specified range


Expressions Description

[abc] Find any of the characters inside the brackets

[^abc] Find any character, not inside the brackets

[0-9] Find any of the digits between the brackets 0 to 9

[^0-9] Find any digit not in between the brackets

(x | y) Find any of the alternatives between x or y separated with |

Regular Expression Metacharacters are characters with a special


meaning:
Metacharacter Description

Search single characters, except line terminator or


\.
newline.

Find the word character i.e. characters from a to z, A to Z,


\w
0 to 9

\d Find a digit

Search non-digit characters i.e all the characters except


\D
digits

\s Find a whitespace character


Metacharacter Description

\S Find the non-whitespace characters.

\b Find a match at the beginning or at the end of a word

Find a match that is not present at the beginning or end of


\B
a word.

\0 Find the NULL character.

\n Find the newline character.

\f Find the form feed character

\r Find the carriage return character

\t Find the tab character

\v Find the vertical tab character

Find the Unicode character specified by the hexadecimal


\uxxxx
number xxxxx

Regular Expression Quantifiers are used to define quantitiesoccurrence


Quantifier Description

n+ Match any string that contains at least one n

n* Match any string that contains zero or more occurrences of n

n? Match any string that contains zero or one occurrence of n

Find the match of any string that contains a sequence of m, X


m{X}
times

Find the match of any string that contains a sequence of m, X to


m{X, Y}
Y times
Quantifier Description

Find the match of any string that contains a sequence of m, at


m{X,}
least X times

m$ Find the match of any string which contains m at the end of it

Find the match of any string which contains m at the beginning


^m
of it

Find the match of any string which is not followed by a specific


?!m
string m.

Regular Expression Object Properties:


Property Description

constructor Return the function that created the RegExp object’s prototype

global Specify whether the “g” modifier is set or not

ignorecase Specify whether the “i” modifier is set or not

lastindex Specify the index at which to start the next match

multiline Specify whether the “m” modifier is set or not

source Return the text of RegExp pattern

Regular Expression Object Methods:


Method Description

compile() Used to compile the regular expression while executing of script

exec() Used to test for the match in a string.

test() Used to test for a match in a string

toString() Return the string value of the regular expression


Use Cases of Regular Expressions
1. Validating Email Addresses
Regular expressions are frequently used for validating emails. Here’s an
example that matches most email formats

let regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;


console.log(regex.test("[email protected]"));

Output
true

2. Extracting Specific Data from a String


You can use regular expressions to extract specific data from a string, like
extracting all numbers from a text.

let regex = /\d+/g;


let res = "There are 123 apples and 456 oranges".match(regex);
console.log(res);

Output
[ '123', '456' ]

3. Replacing Substrings
Regular expressions are often used in replacing certain substrings in text.

let regex = /foo/g;


let res = "foo bar foo".replace(regex, "baz");
console.log(res);

Output
baz bar baz

introduction to AngularJS
AngularJS is a popular open-source framework that simplifies web
development by creating interactive single-page applications (SPAs).
Unlike traditional websites that load new pages for each click, SPAs offer
a smoother user experience by updating content on the same page.
AngularJS makes this possible by transforming static HTML into dynamic
content that adapts to user interactions. Features like data binding and
dependency injection streamline development, saving you time and effort.
With regular updates and a large community, AngularJS ensures your
web applications stay modern and efficient.
Why Choose AngularJS?
1. Easy to Work With: AngularJS requires only basic knowledge of
HTML, CSS, and JavaScript. You don’t need to be an expert; just bring
your curiosity and creativity.
2. Time-Saving Components: AngularJS allows you to work with
reusable components, saving time and reducing unnecessary code.
Components are the building blocks of your application.
3. Ready-to-Use Templates: AngularJS leverages plain HTML
templates, which it compiles and makes ready for use. No complex
setup—just write your HTML and let AngularJS do the heavy lifting.
4. Directives: AngularJS extends HTML with custom elements and
attributes called directives. These enable you to create reusable
components and define custom behaviors for your application.
Directives make it easier to manipulate the DOM, handle events, and
encapsulate complex UI logic within a single component.

Key Features of AngularJS


1. Model-View-Controller (MVC) Architectur e:
 Model: Manages data and logic, responding to requests from the
view and instructions from the controller.
 View: Displays application data to users.
 Controller: Orchestrates communication between the model and
view, updating the model based on user interactions.
2. Filters and Data Transformation:
 AngularJS provides powerful filters for transforming data before
displaying it in templates. Common filters include filter, orderBy,
and currency.
 You can also create custom filters tailored to your application’s
needs.
3. Routing and Single-Page Applications (SPAs):
 Implement client-side routing to create SPAs.
 Handle route parameters and navigation seamlessly.
4. Services and Dependency Injection:
 Services are reusable components that provide specific
functionality.
 Dependency injection ensures loose coupling between components,
making your code more maintainable.
5. Custom Directives and Components:
 Build reusable components using custom directives.
 Isolate scope and communicate between components.
6. Testing AngularJS Applications:
 Write unit tests using Jasmine and Karma.
 Explore end-to-end testing with Protractor.
7. Advanced Topics:
 Dive into promises and asynchronous programming.
 Interact with RESTful APIs.
 Optimize performance and follow best practices.
Applications of AngularJS
1. Dynamic Forms:
 AngularJS excels at creating dynamic forms with real-time validation
and feedback.
2. Real-Time Dashboards:
 Build interactive dashboards that update in real time based on user
interactions.
3. Collaborative Apps:
 AngularJS is perfect for chat applications and collaborative
document editing.
4. E-Commerce Platforms:
 Create seamless shopping experiences with AngularJS-powered
product catalogs and checkout processes.
Advantages of AngularJS
 It facilitates the Two-way Binding that helps to render correspondingly
the changes made to the view or the model.
 It helps to create a responsive web application, along with providing
the prototyping that can be utilized to load the application faster.
 It uses the concept of directive that helps to add functionality to the
application. For this, the overall length of the code reduces along with
discarding the repetition of the code that is specific to perform the
particular task.
AngularJS Expressions
In this article, we will see the Expressions in AngularJS, along with
understanding their implementation through the examples.
Expressions in AngularJS are used to bind application data to HTML.
The expressions are resolved by AngularJS and the result is returned
back to where the expression is written. The expressions in AngularJS are
written in double braces: {{ expression }}. They behave similar to ng-
bind directives: ng-bind="expression".
Syntax:
{{ expression }}
Example 1: This example displays the name that we feed in the ng-init
directive.

<!DOCTYPE html>
<html>

<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<title>AngularJS Expression</title>
</head>

<body style="text-align:center">
<h1 style="color:green">GeeksforGeeks</h1>
<h3>AngularJS Expressions</h3>
<div ng-app=""
ng-init="name='GeeksforGeeks'">
<p> {{ name }} is a portal for geeks.</p>
</div>
</body>
</html>
Output:

Example 2: This example displays the content of the object that we feed
in the ng-init directive.

<!DOCTYPE html>
<html>

<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<title>AngularJS Expression</title>
</head>

<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h3>AngularJS Expressions</h3>
<div ng-app=""
ng-init="sort={one:'quick sort',
two:'merge sort',
three:'bubble sort'}">

<p> Sorting Algorithms:</p>


<ul>
<li>{{ sort.one }}</li>
<li>{{ sort.two }}</li>
<li>{{ sort.three }}</li>
</ul>
</div>
</body>

</html>
Output:

Example 3: This example illustrates the implementation of the objects


with the Expression in AngularJS.

<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>

<body>
<center>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h3 style="color:green">
AngularJS Expressions
</h3>
<div ng-app="" ng-init="data={Course:'AngularJS',
topic:'Expression'}">

<p>This is
<span ng-bind="data.Course"></span>
<span ng-bind="data.topic"></span>
Tutorial
</p>

</div>
</center>
</body>

</html>
Output:

Difference between AngularJS Expression & Javascript Expression:


Parameters Angularjs Expression JavaScript Expression

Angular expressions are JavaScript expressions are


Context evaluated against a scope evaluated against the global
object. window.
Parameters Angularjs Expression JavaScript Expression

JavaScript expression tries to


In Angular, expression
evaluate undefined properties
Forgiving evaluation is forgiving to
and generates ReferenceError
undefined and null.
or TypeError.

Control flow statements cannot


Control flow statements can
Control Flow be used in angularjs
be used in JavaScript
Statements expressions, i.e, loop,
expressions
conditional, or exception

Angular Expressions do not


The function declaration is
Function allow function declaration, not
allowed in JavaScript
Declarations even inside the ng-init
expressions
directive.

Bitwise, Comma, In an Angular expression, You can use Bitwise, or void


And Void Bitwise or void operators operators in a JavaScript
Operators cannot be used. expression.

Angular expressions can work JavaScript expressions do not


Filter with filter work with filter

One-time binding is supported JavaScript expressions do not


One time
by AngularJS. To create one- allow one-time binding
binding
time binding use :: expression.

You might also like