Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

UNIT-3 Javascript: Introduction Java Script

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 45

UNIT-3

JAVASCRIPT
INTRODUCTION JAVA SCRIPT:

Script means small piece of code. Java script you can easily create
interactive web pages. It is designed to add interactivity to HTML
pages. Scripting languages are two kinds one is client-side other one
is servers-side scripting. In general client-side scripting is used for
verifying simple validation at client side, server-side scripting is used
for database verifications. VBScript, java script and J script are
examples for client-side scripting and ASP,JSP, servlets etc. are
examples of server-side scripting.
Web pages are two types
1. Static web page
2. Dynamic webpage
Static web page where there is no specific interaction with the
client
Dynamic web page which is having interactions with client and as
well as
validations can be added.
Simple HTML script is called static web page, if you add script to
HTML page
it is called dynamic page. Netscape navigator developed java script.
Microsoft‟s version of java script is J script.
Java script code as written between <script> ----</script>tags
All java script statements end with a semicolon
Java script ignores white space
 Java script is case sensitive language
Script program can save as either. Js or. html
Similarities between java script and java:
1. Both java script and java having same kind of operators
2. Java script uses similar control structures of java
3. Nowadays both are used as languages for use on internet.
4. Labeled break and labeled continue both are similar

1
Difference between java script and java:
1. Java is object –oriented programming language where as java
script is object-based
programming language.
2. Java is full –featured programming language but java script is not.
3. Java source code is first compiled and the client interprets the
code. Java script code
is not compiled, only interpreted.
4. Inheritance, polymorphism, threads are not available in JavaScript.
The syntax of the script tag is as follows:
<script language=‟‟scripting language name‟‟>
-----------------------------------------
</script>
The language attribute specifies the scripting language used in the
script. Both Microsoft internet explorer and Netscape navigator use
java script as the default scripting language. The script tag may be
placed in either the head or the body or the body of an HTML
document.
Ex: <script language=‟‟java script‟‟>
-------------
--------------
-----------
</script>
Variable declaration in java script:
Variables are declared with the var key word
Var variable name=value
Ex: var x=20
The variable is preceded by the var, it is treated as local variable
otherwise
variable is treated as global variable.
web technologies
Comments in java script:
Single line comment- //
Multi-line comment- /**/
operators in java script:

2
Arithmetic operators
Relational operators
Logical operators
Assignment operator
Increment decrement operators
Conditional operator (ternary)
Bitwise operators
Control structures:
 If statement
 Switch
 While
 Do-while
 For
 Break
 Continue
Control structures syntax and working as same as java language.
Basics Of JavaScript:

JavaScript is an object-based scripting language which is lightweight and


cross-platform.

JavaScript is not a compiled language, but it is a translated language.


The JavaScript Translator (embedded in the browser) is responsible for
translating the JavaScript code for the web browser.

JavaScript is used to create client-side dynamic pages.

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
3
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

4
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)

5
JavaScript Object by object literal

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

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

 By creating instance of Object

The syntax of creating object directly is given below:

1. var objectname=new Object();  

Here, new keyword is used to create object.

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.

JavaScript Object Methods

The various methods of Object are as follows:

S.No Methods Description

1 Object.assign() This method is used to


copye numerable 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 behavioural

6
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

7
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
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.

8
20 Object.values() This method returns an

array of values.

Primitives:
JavaScript allows us to work with primitives (strings, numbers, etc.) as if
they were objects. They also provide methods to call as such. We will
study those soon, but first we’ll see how it works because, of course,
primitives are not objects (and here we will make it even clearer).
Let’s look at the key distinctions between primitives and objects.
A primitive
 Is a value of a primitive type.
 There are 7 primitive
types: string, number, bigint, boolean, symbol, null and undefined.
An object
 Is capable of storing multiple values as properties.
 Can be created with {}, for instance: {name: "John", age: 30}. There are
other kinds of objects in JavaScript: functions, for example, are objects.
Objects are “heavier” than primitives. They require additional resources
to support the internal machinery.

A primitive as an object
Here’s the paradox faced by the creator of JavaScript:
 There are many things one would want to do with a primitive like a string
or a number. It would be great to access them using methods.
 Primitives must be as fast and lightweight as possible.
The solution looks a little bit awkward, but here it is:
1. Primitives are still primitive. A single value, as desired.
2. The language allows access to methods and properties of strings,
numbers, booleans and symbols.
3. In order for that to work, a special “object wrapper” that provides the
extra functionality is created, and then is destroyed.

9
The “object wrappers” are different for each primitive type and are
called: String, Number, Boolean and Symbol. Thus, they provide
different sets of methods.
For instance, there exists a string method str.toUpperCase() that returns
a capitalized str.
Here’s how it works:
let str = "Hello";

alert( str.toUpperCase() ); // HELLO


Simple, right? Here’s what actually happens in str.toUpperCase():
1. The string str is a primitive. So in the moment of accessing its property, a
special object is created that knows the value of the string, and has
useful methods, like toUpperCase().
2. That method runs and returns a new string (shown by alert).
3. The special object is destroyed, leaving the primitive str alone.
So primitives can provide methods, but they still remain lightweight.

Expressions and operators:


Operators
JavaScript has the following types of operators. This section describes
the operators and contains information about operator precedence.

 Assignment operators
 Comparison operators
 Arithmetic operators
 Bitwise operators
 Logical operators
 String operators
 Conditional (ternary) operator
 Comma operator
 Unary operators
 Relational operators
JavaScript has both binary and unary operators, and one special ternary
operator, the conditional operator. A binary operator requires two
operands, one before the operator and one after the operator:

10
operand1 operator operand2

Copy to Clipboard

For example, 3+4 or x*y.

A unary operator requires a single operand, either before or after the


operator:

operator operand

Copy to Clipboard

or

operand operator

Copy to Clipboard

For example, x++ or ++x.

Assignment operators
An assignment operator assigns a value to its left operand based on the
value of its right operand. The simple assignment operator is equal (=),
which assigns the value of its right operand to its left operand. That is, x
= y assigns the value of y to x.

There are also compound assignment operators that are shorthand for
the operations listed in the following table:

Name Shorthand operator Meaning

Assignment x=y x=y

Addition assignment x+=y x=x+y

Subtraction assignment x-=y x=x-y

Multiplication assignment x*=y x=x*y

Division assignment x/=y x=x/y

11
Remainder Assignment x%=y x=x%y

Exponentiation Assignment x**=y x=x**y

Left Shift Assignment x<<=y x=x<<y

Right Shift Assignment x>>=y x=x>>y

Unsigned RighShift Assignment x>>>=y x=x>>y

BitWise AND assignment x&=y x=x&y

Bitwise XOR assignment x^=y x=x^y

Bitwise OR assignment x|=y x=x|y

Loginal AND assignment x&&=y x&&(x=y)

Logical OR assignment x||=-y x||(x=y)

Logical Nullish Assignment x??=y x??(x=y)

Control Statement
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.

12
 Iterative Statements (Loop): Until and unless the expression or

the condition given is satisfied, these statements repeat

themselves.

Control Statement in JavaScript with Example


let’s understand these statements along with examples:

1. Conditional Statements
This is where the flow of the execution in a program is decided.

Conditional Statements decide the next step based of the result.

Conditional statement results in either True or False. Whatever the

condition is passed, if that is true, then the program moves to the next

step and if the condition is False, then 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 is executed if the condition provided is satisfied.

 Popular Course in this category

Syntax:

13
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 you can see, when the condition is satisfied in IF-ELSE, the first block

of code will be executed and if the condition isn’t satisfied, the second

block of code will be executed.

14
 SWITCH

A switch statement is similar to IF and is of use when you need to

execute 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, 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:

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

The above code contains an expression at the very beginning, which is

check and compared with the cases included. If the expression passed

matches with the case a, the code block inside the case is executed.

The same applies for case b and n, and when the expression passed

matches with none of the cases mentioned, it code enters default case

and the code under 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, for any programming language, is a powerful tool in order to

execute a set of instructions, repeatedly, while the expression passed is

satisfied. A very basic example can be, to print “Hello World” for 10

times. Now, writing the same print statement with “Hello world“ for 10

straight times will be time-consuming and will impact the execution time.

And this is where looping comes handy. There are three Iterative

statements: WHILE, DO-WHILE and FOR. Let’s understand each with

syntax.

  WHILE
16
one of the control flow statement, which executes a code block when the

condition is satisfied. But unlike IF, while keeps repeating itself until the

condition is satisfied. Difference between IF and while can be, IF

executes code ‘if’ the condition is satisfied while the 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 then checks for the condition.

Syntax:

while

17
//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 for 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 initialize, it starts the loop, here a declared variable is used. Then

the exit condition for the loop is checked in condition part. When this

condition returns true, the code block inside is executed. When, in case,

if the condition returns false or fails, it goes to increment/decrement part

and the variable is assigned an updated value. Values are updated until

the condition is satisfied.


18
ArrayS:
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:

1. var arrayname=[value1,value2.....valueN];  
As you can see, values are contained inside [ ] and separated by ,
(comma).

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.

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.

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

19
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.

20
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

21
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


initial) left

to right and reduces 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.

22
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 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

23
The syntax of declaring function is given below.

1. function functionName([arg1, arg2, ...argN]){  
2.  //code to be executed  
3. }  
JavaScript Functions can have 0 or more arguments.

JavaScript Function Arguments

Function with Return Value

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.

24
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.

Constructor:
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: super keyword

The super keyword is used to call the parent class constructor

Expressions
Below is the example of the JavaScript Regular Expressions.
 Example:

<script>

function GFGFun() {

    var str = "Visit geeksforGeeks";

    var n = str.search(/GeeksforGeeks/i);

    document.write(n);

25
}

GFGFun();

</script>

Pattern Matching Using Regular


Expression:
A regular expression is a sequence of characters that forms a search
pattern. The search pattern can be used for text search and text to
replace operations. 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:
var patt = /GeeksforGeeks/i;
Explanation:
/GeeksforGeeks/i is a regular expression.
GeeksforGeeks is a pattern (to be used in a search).
i is a modifier (modifies the search to be Case-Insensitive).

Regular Expression Modifiers :


Modifiers can be used to perform multiline searches:
Examples:
Expression
s Description

[abc] Find any of the character inside the brackets

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

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

26
Expression
s Description

with |
Regular Expression Patterns :
Metacharacters are characters with a special meaning:
Examples:
Metacharacte
r Description

\d Used to find a digit

\s Used to find a whitespace character

Used to find a match at beginning or at the end of a


\b word

Used to find the Unicode character specified by the


\uxxxx hexadecimal number xxxxx
Quantifiers define quantities:
Examples:
Quantif
ier Description

Used to match any string that contains at least


n+ one n

Used to match any string that ccontains zero or


n* more occurrences of n

Used to matches any string that contains zero or


n? one occurrences of n

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

27
Quantif
ier Description

returns the position of the match.


The replace() method returns a modified string where the pattern is
replaced.
Using String search() With a Regular Expression :
Use a regular expression to do a case-insensitive search for
“GeeksforGeeks”

in a string:

Expression :
Use a case insensitive regular expression to replace gfG with
GeeksforGeeks in a string:
Example:

<script>

function myFunction() {

    // input string

    var str = "Please visit gfG!";

    // replacing with modifier i

    var txt = str.replace(/gfg/i, "geeksforgeeks");

    document.write(txt);

AngularJS Expressions
28
In AngularJS, expressions are used to bind application data to HTML.
AngularJS resolves the expression, and return the result exactly where
the expression is written.

Expressions are written inside double braces {{expression}}.They can


also be written inside a directive:

1. ng-bind="expression".  

AnularJS expressions are very similar to JavaScript expressions. They


can contain literals, operators, and variables. For example:

Eg:{{ 5 + 5 }} or {{ firstName + " " + lastName }}  

Difference between AngularJS Expressions and JavaScript expressions:

o AngularJS expressions can be written inside HTML, while


JavaScript expressions cannot.
o AngularJS expressions support filters, while JavaScript
expressions do not.
o AngularJS expressions do not support conditionals, loops, and
exceptions, while JavaScript expressions do.

 Any unit of code that can be evaluated to a value is an expression.


 Since,expressions produce values,they can appear anywhere in a
program where javascript expects a value such as the arguments
of a function invocation.
 Expressions are used to bind application data to HTML.
 Expressions are written inside double curly braces such as
in{{expression}}.
 Expressions behave similar to ngbind directives.
 AngularJS exppressions are pure Javascript expressions and
output the data where they are used.
 AngularJS numbers are similar to JavaScript numbers.
 AngularJS expressions and JavaScript expressions both can
contain literals, operators and variables.

$eval:
The Angular JS $eval method is used to executes the AngularJS
expression on the current scope and returns the result.

29
In AngularJS,expressions are similar to JavaScript code snippets
that are usually placedin bindings such as {{expression}}.

AngularJS used internally $eval to resolve AngularJS


expressions,such as {{variable}}.

The $eval method takes AngularJS expression and local variable


object as parameter.

Syntax:

$eval([expression], [locals]);

$eval don’t evaluate JavaScript;they evaluate AngularJS


expression.

The $eval function allows one to evaluate expressions from within


the controller itself.

This function is used to add 2 numbers and make it available in the


scope object shoe that it can be shown in the view.

Strings:
The JavaScript String is an object that represents a sequence of
characers.

There are 2 ways to create string in JavaScript

1. By string literal

2. By string object(using new keyword)

1) By string Literal:

The string literal is created using double quotes.the syntax of


creating string using string literal is given below:

var stringname=”string value”;

Example:

30
<script>

Var str=”This is string literal”;

Document.write(str);

</script>

2) By string object(using new keyword):

The syntax of creating string object using new keyword is given


below:

Var stringname=new String(“string literal”);

Here, the new keyword is used to create instance of string.

Example:

<script>

Var stringname=new String(“hello javascript string”);

Document.write(stringname);

</script>

String Methods:

Methods Description

31
charAt() It provides the char value
present at the specified index.

charCodeAt() It provides the Unicode value of


a character present at the
specified index.

concat() It provides a combination of two


or more strings

indexOf() It provides the position of a char


value present in the given
string.

lastIndexOf() It provides the position of char


value present in the given string
by searching a character from
the last position.

search() It searches a specified regular


expression in a given string and
returns its position if a match
occurs.

match() It searches a specified regular


expression in a given string and
returns that regular expression
if a match occurs.

replace() It replaces a given string with


the specified replacement.

substr() It is used to fetch the part of the


given string on the basis of the
specified starting position and
length.

substring() It is used to fetch the part of the


given string.it allows us to

32
assign positive as well negative
index.

toLowerCase() It coverts the given string into


lowercase letter.

toLocaleLowerCase() It converts the given string into


lowercase letter on the basis of
host?s current locale.

toString() It provides a string representing


the particular object.

valueOf() It provides the primitive value of


string object.

split() It splits a string into substring


array, then returns that newly
created array.

trim() It trims the white space from the


left and right side of the string.

toUpperCase() It converts the given string into


uppercase letter.

toLocaleUpperCase() It converts the given string into


uppercase letter on the basis of
host?s current locale.

slice() It is used to fetch the part of the


given string. It allows us to
assign positive as well as
negative index.

1.JavaScript String charAt(index) Method

The JavaScript String charAt() method returns the character at the given
index.

1. <script>  
33
2. var str="javascript";  
3. document.write(str.charAt(2));  
4. </script>  
Output: v

2) JavaScript String concat(str) Method

The JavaScript String concat(str) method concatenates or joins two


strings.

1. <script>  
2. var s1="javascript ";  
3. var s2="concat example";  
4. var s3=s1.concat(s2);  
5. document.write(s3);  
6. </script>  
Output : javascript concat example

3) JavaScript String indexOf(str) Method

The JavaScript String indexOf(str) method returns the index position of


the given string.

1. <script>  
2. var s1="javascript from javatpoint indexof";  
3. var n=s1.indexOf("from");  
4. document.write(n);  
5. </script>  
Output : 11

4) JavaScript String lastIndexOf(str) Method

The JavaScript String lastIndexOf(str) method returns the last index


position of the given string.

1. <script>  
2. var s1="javascript from javatpoint indexof";  
3. var n=s1.lastIndexOf("java");  
4. document.write(n);  

34
5. </script>  
Output : 16

5) JavaScript String toLowerCase() Method

The JavaScript String toLowerCase() method returns the given string in


lowercase letters.

1. <script>  
2. var s1="JavaScript toLowerCase Example";  
3. var s2=s1.toLowerCase();  
4. document.write(s2);  
5. </script>  
Output : javascript tolowercase example

6) JavaScript String toUpperCase() Method

The JavaScript String toUpperCase() method returns the given string in


uppercase letters.

1. <script>  
2. var s1="JavaScript toUpperCase Example";  
3. var s2=s1.toUpperCase();  
4. document.write(s2);  
5. </script>  
Output : JAVASCRIPT TOUPPERCASE EXAMPLE

7) JavaScript String slice(beginIndex, endIndex) Method

The JavaScript String slice(beginIndex, endIndex) method returns the


parts of string from given beginIndex to endIndex. In slice() method,
beginIndex is inclusive and endIndex is exclusive.

1. <script>  
2. var s1="abcdefgh";  
3. var s2=s1.slice(2,5);  
4. document.write(s2);  
5. </script>  
Output : cde

35
8) JavaScript String trim() Method

The JavaScript String trim() method removes leading and trailing


whitespaces from the string.

1. <script>  
2. var s1="     javascript trim    ";  
3. var s2=s1.trim();  
4. document.write(s2);  
5. </script>  
Output : javascript trim

9) JavaScript String split() Method

1. <script>  
2. var str="This is JavaTpoint website";  
3. document.write(str.split(" ")); //splits the given string.  
4. </script>  

Form Validation:
AngularJS performs form validation on the client-side. AngularJS
monitors the state of the form and input fields (input, text-area, select),
and notify the user about the current state. AngularJS also holds
information about whether the input fields have been touched, modified,
or not.
Form input fields have the following states:
 $untouched: It shows that field has not been touched yet.
 $touched: It shows that field has been touched.
 $pristine: It represents that the field has not been modified yet.
 $dirty: It illustrates that the field has been modified.
 $invalid:It specifies that the field content is not valid.
 $valid:It specifies that the field content is valid.
These all are the properties of the input field which can be either true or
false.
Forms have the following states:
 $pristine: It represents that the fields has not been modified yet.
 $dirty: It illustrates that one or more fields has been modified.
 $invalid:It specifies that the form content is not valid.
 $valid:It specifies that the form content is valid.
 $submitted:It specifies that the form is submitted.

36
These all are the properties of the form which can be either true or
false.
This states can be used to show meaningful messages to the user.
Custom validation:To create your own validation function add a new
directive to your application, and deal with the validation inside a
function with certain specified arguments.
Example:

AngularJS Forms:
The HTML form is a collection of input controls where user can
enter the data. Here, you will learn how to display AngularJS form
and submit the data.

An AngularJS Form Example

We will create following Student Information form with submit and


reset functionality.

37
Sample AngularJS Form

The following is a step by step explanation of the above example:

1. Create an HTML page and wrap all the necessary input controlls
into <form> tag.
2. Create the AngularJS application module in the <script> tag.
3. Create studentController in application module.
4. Create originalStudent object and attach to the $scope with
required properties. This will stay unchanged during entire life
cycle.
5. Create new student object and attach to the $scope and copy all
the properties and values from originalStudent. This student object
will be bound to the form using ng-model directive. Therefore, if
user changes form values then the student object will also get
changed.
6. Create submitStudnetForm function which will get called when
user submits the form using Submit button. Here, send http POST
request to the remote server to submit the data using $http
service.

38
7. Create resetForm() function, which will reset the form values to the
originalStudent values by copying it to student object.
8. Apply ng-app, ng-controller directives.
9. Apply ng-model directives to each HTML input element to bind
appropriate properties of student object.
10. Apply ng-submit directive to form which will call
submitStudentForm() on the form submit event.
11. Apply ng-click directive to reset button which will call
resetForm() on the button click event.

An AngularJS form can be submitted using either ng-submit or ng-click


directive but not both.

Ng-submit: Binds angular expression to onsubmit event when form


does not include action attribute.

Ng-click: Binds angular expression to onclick event.

What is SPA (Single page application)


in AngularJS?
Traditionally, applications were Multi-Page Application (MPA) where with
every click a new page would be loaded from the server. This was not
only time consuming but also increased the server load and made the
website slower. AngularJS is a JavaScript-based front-end web
framework based on bidirectional UI data binding and is used to design
Single Page Applications. Single Page Applications are web applications
that load a single HTML page and only a part of the page instead of the
entire page gets updated with every click of the mouse. The page does
not reload or transfer control to another page during the process. This
ensures high performance and loading pages faster. Most modern
applications use the concept of SPA. In the SPA, the whole data is sent
to the client from the server at the beginning. As the client clicks certain
parts on the webpage, only the required part of the information is fetched
from the server and the page is rewritten dynamically. This results in a
lesser load on the server and is cost-efficient. SPAs use AJAX and
HTML5 to create a fluid and responsive Web applications and most of
the work happens on the client-side. Popular applications such as
Facebook, Gmail, Twitter, Google Drive, Netflix, and many more are
examples of SPA.
Advantages:

39
 Team collaboration
Single-page applications are excellent when more than one developer
is working on the same project. It allows backend developers to focus
on the API, while the frontend developers can focus on creating the
user interface based on the backend API.
 Caching
The application sends a single request to the server and stores all the
received information in the cache. This proves beneficial when the
client has poor network connectivity.
 Fast and responsive
As only parts of the pages are loaded dynamically, it improves the
website’s speed.
 Debugging is easier
Debugging single page applications with chrome is easier since such
applications are developed using like AngularJS Batarang and React
developer tools.
 Linear user experience
Browsing or navigating through the website is easy.

Disadvantages:

 SEO optimization
SPAs provide poor SEO optimization. This is because single-page
applications operate on JavaScript and load data at once server. The
URL does not change and different pages do not have a unique URL.
Hence it is hard for the search engines to index the SPA website as
opposed to traditional server-rendered pages.
 Browser history
A SPA does not save the users’ transition of states within the website.
A browser saves the previous pages only, not the state transition.
Thus when users click the back button, they are not redirected to the
previous state of the website. To solve this problem, developers can
equip their SPA frameworks with the HTML5 History API.
 Security issues
Single-page apps are less immune to cross-site scripting (XSS) and
since no new pages are loaded, hackers can easily gain access to
the website and inject new scripts on the client-side.
 Memory Consumption
Since the SPA can run for a long time sometimes hours at a time, one
needs to make sure the application does not consume more memory
than it needs. Else, users with low memory devices may face serious
performance issues.

40
 Disabled Javascript
Developers need to chalk out ideas for users to access the
information on the website for browsers that have Javascript disabled.
When to use SPA
SPAs are good when the volume of data is small and the website that
needs a dynamic platform. It is also a good option for mobile
applications. But businesses that depend largely on search engine
optimizations such as e-commerce applications must avoid single-page
applications and opt for MPAs.
<!DOCTYPE html>

<!--ng-app directive tells AngularJS that myApp

    is the root element of the application -->

<html ng-app="myApp">

    <head>

        <!--import the angularjs libraries-->

        <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>

        <!--hg-template indicates the pages 

            that get loaded as per requirement-->

        <script type="text/ng-template" 

                id="first.html">

            <h1>First Page</h1>

            <h2 style="color:green">

                Welcome to GeeksForGeeks

            </h2>

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

        </script>

        <script type="text/ng-template" 

                id="second.html">

            <h1>Second Page</h1>

            <h2 style="color:green">

                Start Learning With GFG

            </h2>

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

        </script>

        <script type="text/ng-template"

                id="third.html">

            <h1>Third Page</h1>

            <h2 style="color:green">

                Know about us

            </h2>

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

        </script>

        <!--hyperlinks to load different 

              pages dynamically-->

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

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

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

        <!--ng-view includes the rendered template of

            the current route into the main page-->

        <div ng-view></div>

        <script>

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

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

            app.config(function($routeProvider) {

            $routeProvider

            .when('/', {

            templateUrl : 'first.html',

            controller : 'FirstController'

            })

            .when('/second', {

            templateUrl : 'second.html',

            controller : 'SecondController'

            }}

            .when('/third', {

            templateUrl : 'third.html',

            controller : 'ThirdController'

            })

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

            });

            <!-- controller is a JS function that maintains

     application data and behavior using $scope object -->

            <!--properties and methods can be attached to the

                $scope object inside a controller function-->

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

            $scope.message = 'Hello from FirstController';

            });

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

            $scope.message = 'Hello from SecondController';

43
            });

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

            $scope.message = 'Hello from ThirdController';

            });

        </script>

    </body>

</html>

Example :

44
45

You might also like