You are on page 1of 43

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.

What is JavaScript

JavaScript (js) is a light-weight object-oriented programming language which is used by several websites for scripting the webpages.
It is an interpreted, full-fledged programming language that enables dynamic interactivity on websites when applied to an HTML
document. It was introduced in the year 1995 for adding programs to the webpages in the Netscape Navigator browser. Since then,
it has been adopted by all other graphical web browsers. With JavaScript, users can build modern web applications to interact
directly without reloading the page every time. The traditional website uses js to provide several forms of interactivity and simplicity.

Although, JavaScript has no connectivity with Java programming language. The name was suggested and provided in the times
when Java was gaining popularity in the market. In addition to web browsers, databases such as CouchDB and MongoDB uses
JavaScript as their scripting and query language.

Features of JavaScript

There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured programming
language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.

History of JavaScript

In 1993, Mosaic, the first popular web browser, came into existence. In the year 1994, Netscape was founded by Marc Andreessen.
He realized that the web needed to become more dynamic. Thus, a 'glue language' was believed to be provided to HTML to make
web designing easy for designers and part-time programmers. Consequently, in 1995, the company recruited Brendan
Eich intending to implement and embed Scheme programming language to the browser. But, before Brendan could start, the
company merged with Sun Microsystems for adding Java into its Navigator so that it could compete with Microsoft over the web
technologies and platforms. Now, two languages were there: Java and the scripting language. Further, Netscape decided to give a
similar name to the scripting language as Java's. It led to 'Javascript'. Finally, in May 1995, Marc Andreessen coined the first code of
Javascript named 'Mocha'. Later, the marketing team replaced the name with 'LiveScript'. But, due to trademark reasons and certain
other reasons, in December 1995, the language was finally renamed to 'JavaScript'. From then, JavaScript came into existence.
Application of JavaScript

JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt dialog box),
o Displaying clocks etc.

JavaScript Example

1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>

JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike, chair, glass, keyboard,
monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct create objects.

Creating Objects in JavaScript

There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal

The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).


Let’s see the simple example of creating object in JavaScript.

1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>

Output of the above example


102 Shyam Kumar 40000

2) By creating instance of Object

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>

Output of the above example


101 Ravi 50000

3) By using an Object constructor

Here, you need to create function with arguments. Each argument value can be assigned in the current object by using this keyword.

The this keyword refers to the current object

The example of creating object by object constructor is given below.

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>

Output of the above example


103 Vimal Jaiswal 30000
Defining method in JavaScript Object

We can define method in JavaScript object. But before defining method, we need to add property in the function with same name as
method.

The example of defining method in object is given below.

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>

Output of the above example


103SonooJaiswal30000
103 Sonoo Jaiswal 45000

JavaScript Object Methods

The various methods of Object are as follows:

S.No Methods Description

1 Object.assign() This method is used to copy enumerable and own


properties from a source object to a target object

2 Object.create() This method is used to create a new object with the


specified prototype object and properties.

3 Object.defineProperty() This method is used to describe some behavioral


attributes of the property.

4 Object.defineProperties() This method is used to create or configure multiple


object properties.

5 Object.entries() This method returns an array with arrays of the key,


value pairs.

6 Object.freeze() This method prevents existing properties from being


removed.
7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the
specified property of the specified object.

8 Object.getOwnPropertyDescriptors() This method returns all own property descriptors of a


given object.

9 Object.getOwnPropertyNames() This method returns an array of all properties


(enumerable or not) found.

10 Object.getOwnPropertySymbols() This method returns an array of all own symbol key


properties.

11 Object.getPrototypeOf() This method returns the prototype of the specified


object.

12 Object.is() This method determines whether two values are the


same value.

13 Object.isExtensible() This method determines if an object is extensible

14 Object.isFrozen() This method determines if an object was frozen.

15 Object.isSealed() This method determines if an object is sealed.

16 Object.keys() This method returns an array of a given object's own


property names.

17 Object.preventExtensions() This method is used to prevent any extensions of an


object.

18 Object.seal() This method prevents new properties from being


added and marks all existing properties as non-
configurable.

19 Object.setPrototypeOf() This method sets the prototype of a specified object to


another object.

20 Object.values() This method returns an array of values.

Primitives Operations and Expressions

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two types of data types in JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is dynamically used by
JavaScript engine. You need to use var here to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:

1. var a=40;//holding number


2. var b="Rahul";//holding string

JavaScript primitive data types


There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types

The non-primitive data types are as follows:

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:

1. var sum=10+20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
7. JavaScript Arithmetic Operators
8. Arithmetic operators are used to perform arithmetic operations on the operands. The following operators are known as
JavaScript arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200


/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators

The JavaScript comparison operator compares the two operands. The comparison operators are as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators

The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators

The following operators are known as JavaScript logical operators.

Operator Description Example


&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators

The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-else.

, Comma Operator allows multiple expressions to be evaluated as single statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

Expressions

An expression is an unit of code that JavaScript interpreter can parse and compute to produce a value.
There are simple expressions like literal values and complex which are built from simpler ones usually using operators.

Primary expressions
Primary expressions are the simplest expressions. There are three groups of primary expressions: literal values, variable references, and some
keywords.

Literal values
Literal values are constant values:

"text" // a string literal

125 // a number literal

Variable references
Any identifier that appears in the code JavaScript interpreter assumes it is a variable and try to read its value.

x // evaluates to the value of the variable x

price // evaluates to the value of the variable price

undefined // a global variable undefined evaluates to the value undefined

Basic keywords and reserved words


The this
The this evaluates to the current object. It is used in a method to refer to the current object, for example:

this.name

this.displayName()

Other examples:

true // evaluates to the boolean true

false // evaluates to the boolean false

null //evaluate to the null value.

Function expression

Function expression defines a JavaScript function and the value of this expression is newly defined function. For example:

var sum = function (x, y) {

return x + y;
}

var z = sum (3, 4); //7

Object initializer expression

Object initializer creates object with literal notation and the value of this expression is newly created object. It uses curly brackets surrounding
object properties separated by commas. For example:

var obj = {

prop1: "value1",

prop2: 2

};

Array initializer expression

Array initializer creates array with literal notation and the value of this expression is newly created array. It consists of square brackets
surrounding elements separated by commas. For example:

1 var arr = [1, 2, 3];

Object creation expression

Object creation expression creates a new instance of object. It uses the keyword new followed by a constructor invocation.
An example:

1 var obj = new Object();

Property access expression

There are two ways to access a property of an object: either using the object followed by a period and an identifier or using the object (or the
array) followed by square brackets with an identifier inside. It evaluates respectively to the value of an object property or an array element.

1 var obj = {x: 1, y: 2};

2 obj.x // 1
3 obj['y'] // 2

4 var arr = [2, 3];

5 arr[1] // 3

Invocation expression

Invocation expression is used to call a function or a method in JavaScript.

1 func(arg);

2 obj.myMeth(x, y);

Parent object reference expression

Parent object reference is a new added in ECMAScript 2015 expression using the keyword super. It evaluates to a parent object.

1 super(arg1, arg2); // calls the parent constructor

2 super.meth(arg1, arg2); // calls the parent object method

Spread operator

Spread operator named also rest operator allows an iterable to expand in place where multiple arguments (for function calls) or multiple elements
(for array literals) are expected.

Function call

function sum(a, b, c) {

return a + b + c;

var items = [2, 3, 4];

var result = sum(...items); // 9

Array literal
var motorVehicles = ['car', 'motorcycle', 'truck'];

var railedVehicles = ['train', 'tram'];

var vehicles = ['bicke', ...motorVehicles, 'airplane', 'ship', ...railedVehicles];

console.log(vehicles); // [ "bicke", "car", "motorcycle", "truck", "airplane", "ship", "train", "tram" ]

Other expressions

There are many other expressions, such as arithmetic, comparison, logical. These are covered in the chapter on operators.

Control Statements

Type of Control Statement in JavaScript


Every programming language, basically, has two types of control statements as follows:

 Conditional Statements: based on an expression passed, a conditional

statement makes a decision, which results in either YES or NO.

 Iterative Statements (Loop): These statements continue to repeat until the

expression or condition is satisfied.

1. Conditional Statements
Conditional statements in a program decide the next step based on the result. They

result in either True or False. The program moves to the next step if a condition is
passed and true. However, if the condition is false, the program moves to another step.

These statements are executed only once, unlike loop statements.

Following are the different types of Conditional Statements:

IF

When you want to check for a specific condition with the IF condition, the inner code

block executes if the provided condition is satisfied.

Syntax:

if (condition) {

//code block to be executed if condition is satisfied

IF-ELSE

an extended version of IF. When you want to check a specific condition and two

Syntax:

if (condition)

// code to be executed of condition is true

else {

// code to be executed of condition is false

}
As observed in an IF-ELSE statement, when the condition is satisfied, the first block of

code executes, and if the condition isn’t satisfied, the second block of code executes.

SWITCH

A switch statement is similar to IF and is useful when executing one code out of the

multiple code block execution possibilities based on the result of the expression passed.

Switch statements carry an expression, which is compared with values of the following

cases, and once a match is found, the code associated with that case executes.

Syntax:

switch (expression) {

case a:

//code block to be executed

Break;

case b:

//code block to be executed

Break;

case n:

//code block to be executed

Break;

default:

//default code to be executed if none of the above case is executed

The above code contains an expression at the beginning, checked and compared with

the cases included. If the expression passed matches with case a, the code block inside

the case is executed. The same applies to cases b and n, and when the expression
passed matches with none of the cases mentioned, it code enters the default case, and

the code under the default case is executed.

Now that we have understood the conditional statements let’s learn about the second

type, i.e. Iterative Statements.

2. Iterative Statement
Looping is a powerful tool for any programming language to execute instructions

repeatedly while the expression passed is satisfied. A basic example can be printing

“Hello World” 10 times. Writing the same print statement with “Hello world“ for 10

straight times will be time-consuming and impact the execution time. And this is where

looping comes in handy. There are three Iterative statements: WHILE, DO-WHILE,

and FOR. Let’s understand each with syntax.

WHILE

One of the control flow statements, the “while” statement, executes a code block when

the condition is satisfied. The difference between “IF” and “while” is that “IF” executes

code if the condition is satisfied, while “while” continues to repeat itself until the

condition is satisfied, unlike “IF”, which executes code only once if the condition is

satisfied, “while” keeps repeating itself until the condition is satisfied.

Syntax:
while (condition)

//code block to be executed when condition is satisfied

DO-WHILE

Similar to a while loop, with a twist that keeps a condition at the end of the loop. Also

known as Exit Control Loop, DO-WHILE executes the code and checks for the condition.

Syntax:

while

//code block to be executed when condition is satisfied

} (condition)

If the condition at the end is satisfied, the loop will repeat.

FOR

a for loop will execute a code block a number of times. Compared to other loops, FOR is

shorter and easy to debug as it contains initialization, condition, and increment or

decrement in a single line.

Syntax:

for (initialize; condition; increment/decrement)

//code block to be executed

}
With initialization, the loop starts by using a declared variable. Then, the condition part

checks the exit condition for the loop. When this condition returns true, the code block

inside is executed. If the condition returns false or fails, the control moves to the

increment/decrement part, where the variable is updated. The values are updated until

the condition is satisfied.

Arrays

JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1) JavaScript array literal

The syntax of creating array using array literal is given below:

var arrayname=[value1,value2.....valueN];

As you can see, values are contained inside [ ] and separated by , (comma).

Let's see the simple example of creating and using array in JavaScript.

1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Output of the above example

Sonoo
Vimal
Ratan
2) JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

1. var arrayname=new Array();

Here, new keyword is used to create instance of array.

Let's see the example of creating array directly.

1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>
Test it Now

Output of the above example

Arun
Varun
John

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor so that
we don't have to provide value explicitly.

The example of creating object by array constructor is given below.

1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Test it Now

Output of the above example


Jai
Vijay
Smith

JavaScript Array Methods

Let's see the list of JavaScript array methods with their description.

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns the
modified array.

entries() It creates an iterator object and a loop that iterates over each key/value pair.

every() It determines whether all the elements of an array are satisfying the provided
function conditions.

flat() It creates a new array carrying sub-array elements concatenated recursively till
the specified depth.

flatMap() It maps all array elements via mapping function, then flattens the result into a
new array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another array element.

filter() It returns the new array containing the elements that pass the provided
function conditions.

find() It returns the value of the first element in the given array that satisfies the
specified condition.

findIndex() It returns the index value of the first element in the given array that satisfies
the specified condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index of the
first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then loops
through these keys.

lastIndexOf() It searches the specified element in the given array and returns the index of the
last match.

map() It calls the specified function for every array element and returns the new array

of() It creates a new array from a variable number of arguments, holding any type
of argument.
pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to right and reduces
initial) the array to a single value.

reduceRight() It executes a provided function for each value from right to left and reduces
the array to a single value.

some() It determines if any element of the array passes the test of the implemented
function.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified array.

toString() It converts the elements of a specified array into string form, without affecting
the original array.

unshift() It adds one or more elements in the beginning of the given array.

values() It creates a new iterator object carrying values for each index in the array

Functions

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common
task.

JavaScript Function Syntax

The syntax of declaring function is given below.

6.2M

1K

Polymorphism in Java | Dynamic Method Dispatch


1. function functionName([arg1, arg2, ...argN]){
2. //code to be executed
3. }

JavaScript Function can have 0 or more arguments.

JavaScript Function Example

Let’s see the simple example of function in JavaScript that does not has arguments.

1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
Test it Now

Output of the above example

Call function (button)

JavaScript Function Arguments

We can call function by passing arguments. Let’s see the example of function that has one argument.

1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
Test it Now

Output of the above example

Click

Function with Return Value

We can call function that returns a value and use it in our program. Let’s see the example of function that returns value.

1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>
Test it Now

Output of the above example


hello javatpoint! How r u?

JavaScript Function Object

In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the code globally. However, if we
call the constructor directly, a function is created dynamically but in an unsecured way.

Syntax

1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter

arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

JavaScript Function Methods

Let's see function methods with description.

Method Description

apply() It is used to call a function contains this value and a single array of arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and an argument list.

toString() It returns the result in a form of a string.

JavaScript Function Object Examples

Example 1

Let's see an example to display the sum of given numbers.

1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>

Output

7
Example 2

Let's see an example to display the power of provided value.

1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
Test it Now

Output:

Constructors

JavaScript Constructor Method


A JavaScript constructor method is a special type of method which is used to initialize and create an object. It is called when memory
is allocated for an object.

Points to remember

o The constructor keyword is used to declare a constructor method.


o The class can contain one constructor method only.
o JavaScript allows us to use parent class constructor through super keyword.

Constructor Method Example

Let's see a simple example of a constructor method.

1. <script>
2. class Employee {
3. constructor() {
4. this.id=101;
5. this.name = "Martin Roy";
6. }
7. }
8. var emp = new Employee();
9. document.writeln(emp.id+" "+emp.name);
10. </script>
Output:
11. 6.7M
12. 853
13. OOPs Concepts in Java

101 Martin Roy

Constructor Method Example: super keyword


The super keyword is used to call the parent class constructor. Let's see an example.

1. <script>
2. class CompanyName
3. {
4. constructor()
5. {
6. this.company="Javatpoint";
7. }
8. }
9. class Employee extends CompanyName {
10. constructor(id,name) {
11. super();
12. this.id=id;
13. this.name=name;
14. }
15. }
16. var emp = new Employee(1,"John");
17. document.writeln(emp.id+" "+emp.name+" "+emp.company);
18. </script>
Test it Now

Output:

1 John Javatpoint

Pattern Matching using Regular Expressions

A regular expression is a sequence of characters that forms a search pattern.

The search pattern can be used for text search and text replace operations.

What Is a Regular Expression?


A regular expression is a sequence of characters that forms a search pattern.

When you search for data in a text, you can use this search pattern to describe what you are searching for.

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

Regular expressions can be used to perform all types of text search and text replace operations.

Syntax
/pattern/modifiers;
Example
/w3schools/i;

Example explained:
/w3schools/i is a regular expression.

w3schools is a pattern (to be used in a search).

i is a modifier (modifies the search to be case-insensitive).

Using String Methods


In JavaScript, regular expressions are often used with the two string methods: search() and replace().

The search() method uses an expression to search for a match, and returns the position of the match.

The replace() method returns a modified string where the pattern is replaced.

Using String search() With a String


The search() method searches a string for a specified value and returns the position of the match:

Example
Use a string to do a search for "W3schools" in a string:

let text = "Visit W3Schools!";


let n = text.search("W3Schools");

The result in n will be:

Try it Yourself »

Using String search() With a Regular Expression


Example
Use a regular expression to do a case-insensitive search for "w3schools" in a string:

let text = "Visit W3Schools";


let n = text.search(/w3schools/i);

The result in n will be:

6
Using String replace() With a String
The replace() method replaces a specified value with another value in a string:

let text = "Visit Microsoft!";


let result = text.replace("Microsoft", "W3Schools");

Use String replace() With a Regular Expression


Example
Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:

let text = "Visit Microsoft!";


let result = text.replace(/microsoft/i, "W3Schools");

The result in res will be:

Visit W3Schools!

Did You Notice?


Regular expression arguments (instead of string arguments) can be used in the methods above.
Regular expressions can make your search much more powerful (case insensitive for example).

Regular Expression Modifiers


Modifiers can be used to perform case-insensitive more global searches:

Modifier Description

i Perform case-insensitive matching

g Perform a global match (find all matches rather than stopping after the first match)

m Perform multiline matching

Regular Expression Patterns


Brackets are used to find a range of characters:
Expression Description

[abc] Find any of the characters between the brackets

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

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

Metacharacters are characters with a special meaning:

Metacharacter Description

\d Find a digit

\s Find a whitespace character Try it


»

\b Find a match at the beginning of a word like this: \bWORD, or at the end of a
word like this: WORD\b

\uxxxx Find the Unicode character specified by the hexadecimal number xxxx Try it
»

Quantifiers define quantities:

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n Try it »

n? Matches any string that contains zero or one occurrences of n

Using the RegExp Object


In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.

Using test()
The test() method is a RegExp expression method.

It searches a string for a pattern, and returns true or false, depending on the result.

The following example searches a string for the character "e":

Example
const pattern = /e/;
pattern.test("The best things in life are free!");

Since there is an "e" in the string, the output of the code above will be:

true
You don't have to put the regular expression in a variable first. The two lines above can be shortened to one:

/e/.test("The best things in life are free!");

Using exec()
The exec() method is a RegExp expression method.

It searches a string for a specified pattern, and returns the found text as an object.

If no match is found, it returns an empty (null) object.

The following example searches a string for the character "e":

Example
/e/.exec("The best things in life are free!");

Angular Java Script Angular JS Expressions

What is Angular JS Expressions?


Expressions are variables which were defined in the double braces {{ }}. They are very commonly used
within Angular JS

Explain Angular.js Expressions with an example


AngularJS expressions are those that are written inside double braces {{expression}}.
Syntax:

A simple example of an expression is {{5 + 6}}.

Angular.JS expressions are used to bind data to HTML the same way as the ng-bind directive. AngularJS
displays the data exactly at the place where the expression is placed.

Let’s look at an example of Angular.JS expressions.

In this example, we just want to show a simple addition of numbers as an expression.

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>

</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> Guru99 Global Event</h1>

<div ng-app="">
Addition : {{6+9}}
</div>
</body>
</html>
Code Explanation:

1. The ng-app directive in our example is blank as shown in above screenshot. This only means that
there is no module to assign controllers, directives, services attached to the code.
2. We are adding a simple expression which looks at the addition of 2 numbers.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:

From the output,

 It can be seen that the addition of the two numbers 9 and 6 take place and the added value of 15
is displayed.

Angular.JS Numbers
Expressions can be used to work with numbers as well. Let’s look at an example of Angular.JS
expressions with numbers.

In this example, we just want to show a simple multiplication of 2 number variables called margin and
profit and displayed their multiplied value.
Code Explanation:

1. The ng-init directive is used in angular.js to define variables and their corresponding values in the
view itself. It’s somewhat like defining local variables to code in any programming language. In
this case, we are defining 2 variables called margin and profit and assigning values to them.
2. We are then using the 2 local variables and multiplying their values.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:

From the output,


 It can be clearly seen that the multiplication of the 2 numbers 2 and 200 take place, and the
multiplied value of 400 is displayed.

AngularJS Strings
Expressions can be used to work with strings as well. Let’s look at an example of Angular JS expressions
with strings.

In this example, we are going to define 2 strings of “firstName” and “lastName” and display them using
expressions accordingly.

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>

</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> Guru99 Global Event</h1>

<div ng-app="" ng-init="firstName='Guru';lastName='99'">

&nbsp;&nbsp;&nbsp;
First Name : {{firstName}}<br>&nbsp;&nbsp;&nbsp;
last Name : {{lastName}}

</div>

</body>
</html>
Code Explanation:

1. The ng-init directive is used define the variables firstName with the value “Guru” and the variable
lastName with the value of “99”.
2. We are then using expressions of {{firstName}} and {{lastName}} to access the value of these
variables and display them in the view accordingly.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:
Angular.JS Objects
Expressions can be used to work with JavaScript objects as well.

Let’s look at an example of Angular.JS expressions with javascript objects. A javascript object consists of
a name-value pair.

Below is an example of the syntax of a javascript object.

Syntax:

var car = {type:"Ford", model:"Explorer", color:"White"};

In this example, we are going to define one object as a person object which will have 2 key value pairs of
“firstName” and “lastName”

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>

</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> Guru99 Global Event</h1>

<div ng-app="" ng-init="person={firstName:'Guru',lastName:'99'}">

&nbsp;&nbsp;&nbsp;
First Name : {{person.firstName}}<br>&nbsp;&nbsp;&nbsp;
Last Name : {{person.lastName}}

</div>

</body>
</html>
Code Explanation:

1. The ng-init directive is used to define the object person which in turn has key value pairs of
firstName with the value “Guru” and the variable lastName with the value of “99”.
2. We are then using expressions of {{person.firstName}} and {{person.secondName}} to access the
value of these variables and display them in the view accordingly. Since the actual member
variables are part of the object person, they have to access it with the dot (.) notation to access
their actual value.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.
Output:

AngularJS Arrays
Expressions can be used to work with arrays as well. Let’s look at an example of Angular JS expressions
with arrays.

In this example, we are going to define an array which is going to hold the marks of a student in 3
subjects. In the view, we will display the value of these marks accordingly.

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> Guru99 Global Event</h1>

<div ng-app="" ng-init="marks=[1,15,19]">

Student Marks<br>&nbsp;&nbsp;&nbsp;
Subject1 : {{marks[0] }}<br>&nbsp;&nbsp;&nbsp;
Subject2 : {{marks[1] }}<br>&nbsp;&nbsp;&nbsp;
Subject3 : {{marks[2] }}<br>&nbsp;&nbsp;&nbsp;
</div>

</body>
</html>
Code Explanation:

1. The ng-init directive is used define the array with the name “marks” with 3 values of 1, 15 and 19.
2. We are then using expressions of marks [index] to access each element of the array.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:
Difference between expression and $eval
The $eval function allows one to evaluate expressions from within the controller itself. So while
expressions are used for evaluation in the view, the $eval is used in the controller function.

Let’s look at a simple example on this.

In this example,

We are just going to use the $eval function to add 2 numbers and make it available in the scope object so
that it can be shown in the view.

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<div ng-app="sampleApp" ng-controller="AngularController">


<h1> Guru99 Global Event</h1>
{{value}}
</div>
<script>
var sampleApp = angular.module('sampleApp',[]);
sampleApp.controller('AngularController',function($scope){
$scope.a=1;
$scope.b=1;

$scope.value=$scope.$eval('a+b');
});
</script>

</body>
</html>
Code Explanation:

1. We are first defining 2 variables ‘a’ and ‘b’, each holding a value of 1.
2. We are using the $scope.$eval function to evaluate the addition of the 2 variables and assigning
it to the scope variable ‘value’.
3. We are then just displaying the value of the variable ‘value’ in the view.
If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:

AngularJS Form Validation


AngularJS provides client-side form validation. It checks the state of the form and input fields (input, textarea, select), and lets you
notify the user about the current state.

It also holds the information about whether the input fields have been touched, or modified, or not.

Following directives are generally used to track errors in an AngularJS form:

o $dirty - states that value has been changed.


o $invalid - states that value entered is invalid.
o $error - states the exact error.

AngularJS Form Validation Example

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Angular JS Forms</title>
5. <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
6.
7. <style>
8. table, th , td {
9. border: 1px solid grey;
10. border-collapse: collapse;
11. padding: 5px;
12. }
13.
14. table tr:nth-child(odd) {
15. background-color: lightpink;
16. }
17.
18. table tr:nth-child(even) {
19. background-color: lightyellow;
20. }
21. </style>
22.
23. </head>
24. <body>
25.
26. <h2>AngularJS Sample Application</h2>
27. <div ng-app = "mainApp" ng-controller = "studentController">
28.
29. <form name = "studentForm" novalidate>
30. <table border = "0">
31. <tr>
32. <td>Enter first name:</td>
33. <td><input name = "firstname" type = "text" ng-model = "firstName" required>
34. <span style = "color:red" ng-show = "studentForm.firstname.$dirty && studentForm.firstname.$invalid">
35. <span ng-show = "studentForm.firstname.$error.required">First Name is required.</span>
36. </span>
37. </td>
38. </tr>
39.
40. <tr>
41. <td>Enter last name: </td>
42. <td><input name = "lastname" type = "text" ng-model = "lastName" required>
43. <span style = "color:red" ng-show = "studentForm.lastname.$dirty && studentForm.lastname.$invalid">
44. <span ng-show = "studentForm.lastname.$error.required">Last Name is required.</span>
45. </span>
46. </td>
47. </tr>
48.
49. <tr>
50. <td>Email: </td><td><input name = "email" type = "email" ng-model = "email" length = "100" required>
51. <span style = "color:red" ng-show = "studentForm.email.$dirty && studentForm.email.$invalid">
52. <span ng-show = "studentForm.email.$error.required">Email is required.</span>
53. <span ng-show = "studentForm.email.$error.email">Invalid email address.</span>
54. </span>
55. </td>
56. </tr>
57. <tr>
58. <td>
59. <button ng-click = "reset()">Reset</button>
60. </td>
61. <td>
62. <button ng-disabled = "studentForm.firstname.$dirty &&
63. studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
64. studentForm.lastname.$invalid || studentForm.email.$dirty &&
65. studentForm.email.$invalid" ng-click="submit()">Submit</button>
66. </td>
67. </tr>
68. </table>
69. </form>
70. </div>
71. <script>
72. var mainApp = angular.module("mainApp", []);
73. mainApp.controller('studentController', function($scope) {
74. $scope.reset = function(){
75. $scope.firstName = "Sonoo";
76. $scope.lastName = "Jaiswal";
77. $scope.email = "sonoojaiswal@javatpoint.com";
78. }
79. $scope.reset();
80. });
81. </script>
82. </body>
83. </html>

How To Build a Single Page Application Using AngularJS?


Developing an application from scratch is not easy as it seems. Everything should be researched in advance, from choosing
the best framework for the database to a team of developers. Some business persons are concerned about the cost and
search for how much it costs to develop an app, but end with inaccurate figures as the price depends on many factors.
After discussing the below steps, you might know how much time and money is required to develop a single-page
application using the latest framework.

Step 1: Create a Module

Angular follows MVC architecture, so every angular app consists of different modules.

Var app = angular.module(‘myApp’,[]);

Step 2: Define Controller

app.controller('FirstController', function($scope) {

$scope.message = 'Hello from FirstController';

});

Step 3: Deploy the AngularJS script in HTML Code

The module created in the first step and the controller performed in the second step specify both in the ng-controller
attribute.

<!doctype html>

<html ng-app="myApp">

<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

</head>

<body ng-controller="FirstController">

<h1>{{message}}</h1>

<script src="app.js"></script>

</body>

</html>

Step 4: Create an HTML Layout for the Website


Once you successfully create the HTML layout for the website, you need to use the ng-view directive with the one place
where the HTML file of all pages will be placed in the same layout.

<!doctype html>

<html ng-app="myApp">

<head>

<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>

</head>

<body>

<div ng-view></div>

<script src="app.js"></script>

</body>

</html>

Step 5: Configure Routes

A templateUrl and a controller must be specified for each route. In cases where a user attempts to navigate to an unexistent
route, an exception must be handled. Then, the user can be redirected to the “/” route using an “otherwise” function.

var app = angular.module('myApp', ['ngRoute']);

app.config(function($routeProvider) {
$routeProvider

.when('/', {

templateUrl : 'pages/first.html',

controller : 'FirstController'

})

.when('/blog', {

templateUrl : 'pages/second.html',

controller : 'SecondController'

})

.when('/about', {

templateUrl : 'pages/third.html',

controller : 'ThirdController'

})

.otherwise({redirectTo: '/'});

});

Step 6: Time to Build Controllers

app.controller('FirstController', function($scope) {

$scope.message = 'Hello from FirstController';

});

app.controller('SecondController', function($scope) {

$scope.message = 'Hello from SecondController';

});
app.controller('ThirdController', function($scope) {

$scope.message = 'Hello from ThirdController';

});

Step 7: Configuring the HTML Pages

first.html

<h1>First</h1>

<h3>{{message}}</h3>

second.html

<h1>Second</h1>

<h3>{{message}}</h3>

third.html

<h1>Third</h1>

<h3>{{message}}</h3>

Step 8: Add Links to Those HTML Pages

<!doctype html>

<html ng-app="myApp">

<head>

<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>

</head>

<body>

<a href="#/">First</a>

<a href="#/second">Second</a>

<a href="#/third">Third</a>
<div ng-view></div>

<script src="app.js"></script>

</body>

</html>

Step 9: Include the HTML of the Above Pages to Index.html file with Script Tag

<!doctype html>

<html ng-app="myApp">

<head>

<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>

</head>

<body>

<script type="text/ng-template" id="pages/first.html">

<h1>First</h1>

<h3>{{message}}</h3>

</script>

<script type="text/ng-template" id="pages/second.html">

<h1>Second</h1>

<h3>{{message}}</h3>

</script>

<script type="text/ng-template" id="pages/third.html">

<h1>Third</h1>

<h3>{{message}}</h3>

</script>
<a href="#/">First</a>

<a href="#/second">Second</a>

<a href="#/third">Third</a>

<div ng-view></div>

<script src="app.js"></script>

</body>

</html>

That’s it! After successfully performing the above steps, you can easily create single-page applications using Angular and
also simplify many other complex tasks of your projects.

You might also like