0% found this document useful (0 votes)
11 views

Unit-2

The document provides an overview of client-side JavaScript, detailing its features, advantages, limitations, and various applications in web development. It covers essential topics such as JavaScript syntax, variable types, and methods for incorporating JavaScript into HTML documents. Additionally, it discusses JavaScript development tools and how to enable or disable JavaScript in different web browsers.

Uploaded by

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

Unit-2

The document provides an overview of client-side JavaScript, detailing its features, advantages, limitations, and various applications in web development. It covers essential topics such as JavaScript syntax, variable types, and methods for incorporating JavaScript into HTML documents. Additionally, it discusses JavaScript development tools and how to enable or disable JavaScript in different web browsers.

Uploaded by

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

Client-Side Scripting

Unit-2
By
Dr. CH Mahender Reddy
Contents:
• JavaScript: Introduction,
• Functions,
• Arrays,
• DOM,
• Built-in Objects,
• Regular Expression,
• Event handling,
• Validation,
• Dynamic documents
Introduction:
• JavaScript is an object-based scripting language that is lightweight and cross-platform.

• JavaScript is not compiled but translated. The JavaScript Translator (embedded in the browser) is
responsible for translating the JavaScript code.

• JavaScript is a dynamic computer programming language.


• JavaScript (js) is a lightweight object-oriented programming language that is used by several
websites for scripting 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.
Client-side JavaScript:
• Client-side JavaScript is the most common form of the language. The script should be included in
or referenced by an HTML document for the code to be interpreted by the browser.
• It means that a web page need not be a static HTML, but can include programs that interact with
the user, control the browser, and dynamically create HTML content.
• The JavaScript client-side mechanism provides many advantages over traditional CGI(Common
Gateway Interface) server-side scripts.
• For example, you might use JavaScript to check if the user has entered a valid e-mail address in a
form field.
• The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.
• JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other
actions that the user initiates explicitly or implicitly.
Advantages of JavaScript:
• Less server interaction − You can validate user input before sending the page
off to the server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
• Richer interfaces − You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript:
We cannot treat JavaScript as a full-fledged programming language. It lacks the following important
features-

• Client-side JavaScript does not allow the reading or writing of files. This has been kept for security
reasons.

• JavaScript cannot be used for networking applications because there is no such support available.

• JavaScript doesn't have any multithreading or multiprocessor capabilities.


Where JavaScript is used:
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 popup windows and dialog boxes (like alert dialog box, confirm dialog box and
prompt dialog box)
o Displaying clocks etc.
JavaScript Development Tools:
• One of the major strengths of JavaScript is that it does not require expensive development tools.
You can start with a simple text editor such as Notepad. Since it is an interpreted language inside the
context of a web browser, you don't even need to buy a compiler.

• JavaScript editing some tools are listed here −

• Microsoft FrontPage − Microsoft has developed a popular HTML editor called FrontPage.
FrontPage also provides web developers with several JavaScript tools to assist in the creation of
interactive websites.

• Macromedia Dreamweaver MX − Macromedia Dreamweaver MX is a very popular HTML and


JavaScript editor in the professional web development crowd. It provides several handy prebuilt
JavaScript components, integrates well with databases, and conforms to new standards such as
XHTML and XML.

• Macromedia HomeSite 5 − HomeSite 5 is a well-liked HTML and JavaScript editor from


Macromedia that can be used to manage personal websites effectively.
Where is JavaScript Today ?:
• The ECMAScript Edition 5 standard will be the first update to be released in over four years.
JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard, and the difference between the
two is extremely minor.

• The specification for JavaScript 2.0 can be found on the following site: http://www.ecmascript.org/

• JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> tag.

• You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it
is normally recommended that you should keep it within the <head> tags.
• The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script. A simple syntax of your JavaScript will appear as
follows.
<script ...>
JavaScript code
</script>
• The script tag takes two important attributes −

• Language − This attribute specifies what scripting language you are using. Typically, its value
will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased
out the use of this attribute.

• Type − This attribute is what is now recommended to indicate the scripting language in use and
its value should be set to "text/javascript".

• So your JavaScript segment will look like −

<script language="javascript" type="text/javascript">


JavaScript code
</script>
Your First JavaScript Script:
• Let us take a sample example to print out "Hello World".
• We added an optional HTML comment that surrounds our JavaScript code.
• This is to save our code from a browser that does not support JavaScript.
• The “//" signifies a comment in JavaScript,
• Next, we call a function document.write which writes a string into our HTML document.
• This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<script language="javascript" type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
Whitespace and Line Breaks
• JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.

• You can use spaces, tabs, and newlines freely in your program and you are free to format and
indent your programs neatly and consistently which makes the code easy to read and understand.
Semicolons are Optional
• Simple statements in JavaScript are generally followed by a semicolon character, just as they are in
C, C++, and Java.

• JavaScript, however, allows you to omit this semicolon if each of your statements are placed on a
separate line.

• For example, the following code could be written without semicolons.


<script language="javascript" But when formatted in a single line as
type="text/javascript"> follows, you must use semicolons −
<!-- <script language="javascript"
var1 = 10 type="text/javascript">
var2 = 20 <!--
//--> var1 = 10; var2 = 20;
</script> //-->
</script>
Note − It is a good programming
practice to use semicolons.
Case Sensitivity:
• JavaScript is a case-sensitive language. This means that the language keywords, variables, function
names, and any other identifiers must always be typed with a consistent capitalization of letters.

• So the identifiers Time and TIME will convey different meanings in JavaScript.

• NOTE − Care should be taken while writing variable and function names in JavaScript.

• All the modern browsers come with built-in support for JavaScript. Frequently, you may need to
enable or disable this support manually.
JavaScript in Internet Explorer:
• Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −
• Follow Tools → Internet Options from the menu.
• Select Security tab from the dialog box.
• Click the Custom Level button.
• Scroll down till you find Scripting option.
• Select Enable radio button under Active scripting.
• Finally click OK and come out
• To disable JavaScript support in your Internet Explorer, you need to select Disable radio button
under Active scripting.
JavaScript in Firefox:
• Here are the steps to turn on or turn off JavaScript in Firefox −
• Open a new tab → type about: config in the address bar.
• Then you will find the warning dialog. Select I’ll be careful, I promise!
• Then you will find the list of configure options in the browser.
• In the search bar, type javascript.enabled.
• There you will find the option to enable or disable javascript by right-clicking on the value of that
option → select toggle.
• If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it
gets enabled upon clicking toggle.
JavaScript in Chrome:
• Here are the steps to turn on or turn off JavaScript in Chrome −
• Click the Chrome menu at the top right hand corner of your browser.
• Select Settings.
• Click Show advanced settings at the end of the page.
• Under the Privacy section, click the Content settings button.
• In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites to
run JavaScript (recommended)".
JavaScript in Opera:
• Here are the steps to turn on or turn off JavaScript in Opera −
• Follow Tools → Preferences from the menu.
• Select Advanced option from the dialog box.
• Select Content from the listed items.
• Select Enable JavaScript checkbox.
• Finally click OK and come out.
• To disable JavaScript support in your Opera, you should not select the Enable JavaScript
checkbox.
Warning for Non-JavaScript Browsers
If you have to do something important using JavaScript, then you can display a warning
message to the user using <noscript> tags.
You can add a noscript block immediately after the script block as follows −
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the
message from </noscript> will be displayed on the screen.
JavaScript Where To:
The <script> Tag
In HTML, JavaScript code must be inserted between <script> and </script> tags.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>
• There is flexibility given to include JavaScript code anywhere in an HTML document. However,
the most preferred ways to include JavaScript in an HTML file are as follows −
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in an external file and then include in <head>...</head> section.
JavaScript in <head>...</head> section
• If you want to have a script run on some event, such as when a user clicks somewhere, then you
will place that script in the head as follows −
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
JavaScript in <body>...</body> section
• If you need a script to run as the page loads so that the script generates content on the page, then
the script goes in the <body> portion of the document. In this case, you would not have any
function defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
JavaScript in <body> and <head> Sections:
<html> <body>
<head> <script type="text/javascript">
<script type="text/javascript"> <!--
<!-- document.write("Hello World")
function sayHello() { //-->
alert("Hello World") </script>
} <input type="button" onclick="sayHello()"
//--> value="Say Hello" />
</body>
</script>
</head> </html>
JavaScript in External File:
• External scripts are practical when the same code is used in many different web pages.
• JavaScript files have the file extension .js.
• To use an external script, put the name of the script file in the src (source) attribute of a <script>
tag:
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body> Filename.js
.......
</body> function sayHello() {
alert("Hello World")
</html> }
JavaScript Comment:
• The JavaScript comments are a meaningful way to deliver the message.
• It is used to add information about the code, warnings, or suggestions so that end users can easily
interpret the code.
• The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.
• There are two types of comments in JavaScript.
1. Single-line Comment
It is represented by double forward slashes (//).
2. Multi-line Comment
It is represented by a forward slash with an asterisk then an asterisk with a forward
slash. For example: /* your code here */
JavaScript Variable:
• A JavaScript variable is simply the name of the storage location. There are two types of variables
in JavaScript: local variable and global variable.
• There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After the first letter we can use digits (0 to 9), for example, value1.
• JavaScript variables are case sensitive, for example x and X are different variables
• Correct JavaScript variables
var x = 10;
var _value="sonoo";
• Incorrect JavaScript variables
var 123=30;
var *aa=320;
JavaScript local variable:
• A JavaScript local variable is declared inside a block or function. It is accessible within
the function or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
JavaScript global variable:
• A JavaScript global variable is accessible from any function. A variable i.e. declared outside the
function or declared with a window object is known as a global variable. For example:
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
Scope of variables:
var let const

The scope of a var variable is The scope of a let variable is block The scope of a const variable is
functional scope. scope. block scope.

It can be updated and re-declared It can be updated but cannot be re- It cannot be updated or re-declared
into the scope. declared into the scope. into the scope.

It can be declared without It can be declared without It cannot be declared without


initialization. initialization. initialization.

It can be accessed without It cannot be accessed without It cannot be accessed without


initialization as its default value is initialization otherwise it will give initialization, as it cannot be
“undefined”. ‘referenceError’. declared without initialization.
Exp-1: Output: 7
var a = 10
function f() { Exp:3
console.log(a) function f() {
} // It can be accessible any
f(); // where within this function
console.log(a); var a = 10;
Output:10 console.log(a)
10 }
f();
Exp:2 // A cannot be accessible
var a = 10 // outside of function
console.log(a);
// User can re-declare Output:
// variable using var 10
var a = 8 ReferenceError: a is not defined
// User can update var variable
a=7
Exp-1: // defined in if block
let a = 10; console.log(b);
function f() { }
let b = 9 f()
console.log(b); // It prints 10
console.log(a); console.log(a)
} Output:
f(); 9
Output: 9 ReferenceError: b is not defined
10
Exp-3:
Exp-2: let a = 10
let a = 10;
function f() { // It is not allowed
if (true) { let a = 10
let b = 9
// It is allowed
// It prints 9 a = 10
console.log(b); Output:
} Uncaught SyntaxError: Identifier 'a' has already been declared
// It gives error as it
Exp-1:
const a = 10; // It is allowed
function f() { a.prop1 = 3
a=9
console.log(a) // It is not allowed
} a={
f(); b: 10,
Output: prop2: 9
TypeError: Assignment to constant variable. }
Output:
Exp-2: Uncaught SyntaxError: Unexpected identifier
Const a = { Note: Users cannot change the properties of the const
variable, but they can change the value of the properties
prop1: 10,
of the const object.
prop2: 9
}
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, which means you don't need to specify the type of the
variable because it is dynamically used by the JavaScript engine. You need to use var here to
specify the data type. It can hold any type of value such as numbers, strings, etc.
• For example:
• var a=40;//holding number
• var b="Rahul";//holding string
JavaScript primitive data types:

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:

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:
• 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
JavaScript Arithmetic Operators:
• 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.
Control Statements:
• JavaScript supports conditional statements which are used to perform different actions based on
different conditions. Here we will explain the if.. else statement.
• Flow Chart of if-else
• The following flow chart shows how the if-else statement works.
• JavaScript supports the following forms of if..else statement −
• if statement
• if...else statement
• if...else if... statement.
JavaScript If statement:
• It evaluates the content only if the expression is true. The signature of the JavaScript if statement is
given below.

if(expression){
//content to be evaluated
}

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
JavaScript If...else Statement:
• It evaluates the content and whether the condition is true or false. The syntax of JavaScript if-else
statement is given below.
if(expression){
//content to be evaluated if the condition is true
}
else{
//content to be evaluated if the condition is false
}
<script>
var a=20;
if(a%2==0){
document.write("a is even number"); }
else{
document.write("a is odd number"); }
</script>
JavaScript If...else if statement:
• It evaluates the content only if the expression is true from several expressions. The signature of the
JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
The while Loop
• The most basic loop in JavaScript is the while loop
The purpose of a while loop is to execute a
statement or code block repeatedly as long as
an expression is true.
• Once the expression becomes false, the loop
terminates.
The while Loop

• Syntax
• The syntax of while loop in JavaScript is as follows −
while (expression)
{
Statement(s) to be executed if expression is true
}
The do...while Loop
• The do...while loop is similar to
the while loop except that the condition
check happens at the end of the loop.
• This means that the loop will always be
executed at least once, even if the
condition is false.
The do...while Loop
• Syntax
• The syntax for do-while loop in JavaScript is as follows −
Do
{
Statement(s) to be executed;
} while (expression);
The for loop
• The 'for' loop is the most compact form of looping. It includes the
following three important parts −
• The loop initialization where we initialize our counter to a starting
value. The initialization statement is executed before the loop begins.
• The test statement which will test if a given condition is true or not. If
the condition is true, then the code given inside the loop will be
executed, otherwise the control will come out of the loop.
The for loop
The syntax of for loop is JavaScript is as follows −

for (initialization; test condition; iteration


statement)
{
Statement(s) to be executed if test condition is
true
}
The for loop
<html>
<body>
<script type="text/javascript">
var count;
for(count = 0; count < 10; count++)
{
document.write("Current Count : " + count + "<br />");
}
</script>
</body>
</html>
For in loop
• The for...in loop is used to loop through an object's properties. As we
have not discussed Objects yet, you may not feel comfortable with
this loop. But once you understand how objects behave in JavaScript,
you will find this loop very useful.
• Syntax
for (variablename in object)
{
statement or block to execute
}
<html>
<body>
<script type="text/javascript">
var name;
for (name in document)
{
document.write(name + "<br />");
}
</script>
</body>
</html>
Switch case
• You can use multiple if...else if statements, to perform a multiway
branch. However, this is not always the best solution, especially when
all of the branches depend on the value of a single variable.
• Starting with JavaScript 1.2, you can use a switch statement that
handles exactly this situation, and it does so more efficiently than
repeated if...else if statements.
Switch case
Syntax
switch (expression)
{
case condition 1: statement(s) break;
case condition 2: statement(s) break;
...
case condition n: statement(s) break;
default: statement(s)
}
The break statements indicate the end of a
particular case.
JavaScript Popup Boxes
• JavaScript has three kind of popup boxes:
• Alert box
• Confirm box
• Prompt box
Alert Box
• An alert box is often used if you want to make sure information
comes through to the user.
• When an alert box pops up, the user will have to click "OK" to
proceed.
• It is used when a warning message is needed to be produced. When
the alert box is displayed to the user, the user needs to press ok and
proceed.
• Syntax
• window.alert("sometext");
Alert Box
• The window.alert() method can be written without the window prefix.
<html>
<body>
<h2>JavaScript in Body</h2>
<script>
window.alert("Hi Good Morning");
</script>
</body>
</html>
Confirm Box
• It is a type of pop-up box that is used to get authorization or
permission from the user.
• If the user clicks "OK", the box returns true. If the user clicks "Cancel",
the box returns false.
• Syntax
• window.confirm("sometext");
Confirm Box
<html>
<body>
<h2>JavaScript in Body</h2>
<script language="javascript">
var name=window.confirm("are you want to delete");
document.write(name);
</script>
</body>
</html>
Prompt Box
• It is a type of pop-up box that is used to get the user input for further
use.
• After entering the required details user has to click ok to proceed next
stage else by pressing the cancel button user returns the null value.
• If the user clicks "OK" the box returns the input value. If the user
clicks "Cancel" the box returns null.
• Syntax
• window.prompt("sometext","defaultText");
Prompt Box
<html>
<body>
<h2>JavaScript in Body</h2>
<script language="javascript">
var name=window.prompt(“Enter your name");
document.write("My name is " + name);
</script>
</body>
</html>
Addition of Two Numbers
<html>
<body>
<h2>JavaScript in Body</h2>
<script>
var a=window.prompt(“Enter first number",10);
var b=window.prompt(“Enter second number",20);
c=parseInt(a)+parseInt(b);
document.write(“Sum="+c);
</script>
</body>
</html>
JavaScript Functions:
• JavaScript functions are used to perform operations. We can call the JavaScript function many
times to reuse the code.
• Advantage of JavaScript function
• There are mainly two advantages of JavaScript functions.
• Code reusability: We can call a function several times so it saves coding.
• Less coding: It makes our program compact. We don’t need to write many lines of code each
time to perform a common task.
• The syntax of declaring a function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
• JavaScript Functions can have 0 or more arguments.
Why Functions?
• You can reuse code: Define the code once, and use it many times.
• You can use the same code many times with different arguments, to produce different results.
• The () Operator Invokes the Function

• Using the example above, toCelsius refers to the function object, and toCelsius() refers to the
function result.
• Functions Used as Variable Values

• Functions can be used the same way as you use variables, in all types of formulas, assignments,
and calculations.
JavaScript Function Example:
• Let’s see the simple example of a function in JavaScript that does not have arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
JavaScript Function Arguments:
• We can call functions by passing arguments. Let’s see the example of a function that has one
argument.

<script>
function getcube(number=5){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Function with Return Value:
• We can call a function that returns a value and use it in our program. Let’s see the example of a
function that returns value.

<script>
function getInfo(){
return "hello world!! How are you?";
}
</script>
<script>
document.write(getInfo());
</script>
JavaScript Function Object:
• In JavaScript, the purpose of a 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
new Function ([arg1[, arg2[, ....argn]],] functionBody)
• Parameter
• arg1, arg2, ...., argn - It represents the argument used by the function.
• functionBody - It represents the function definition.
JavaScript Function Object Examples:
<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>

<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>
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.


• The JavaScript Function apply() method is used to call a function contains
this value and an argument contains elements of an array. Unlike call()
method, it contains the single array of arguments.
• Syntax:
function.apply(thisArg, [array])
• Parameter
• thisArg - It is optional. The this value is given for the call to a function.
• array - It is optional. It is an array-like object.
<script>
var arr = [7, 5, 9, 1];
var max = Math.max.apply(null, arr);
document.writeln(max);
</script>
Javascript Object
• 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.
• By object literal
• By creating instance of Object directly (using new keyword)
• By using an object constructor (using new keyword)
JavaScript Object by object literal
• The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN}
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
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.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
By using an Object constructor
 The this keyword refers to the current object.
 The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
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.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
Built-in Objects
• JavaScript also has four built-in objects: Array, Date, Math, and String.
• Each object has special-purpose properties and methods associated
with it.
• JavaScript also has constructors for Boolean and Number types.
JavaScript Array
• JavaScript array is an object that represents a collection of elements.
• There are 3 ways to construct array in JavaScript
• By array literal
• By creating instance of Array directly (using new keyword)
• By using an Array constructor (using new keyword)
JavaScript array literal
• The syntax of creating array using array literal is given below:
• var arrayname=[value1,value2.....valueN];
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
JavaScript Array directly (new keyword)
 The syntax of creating an array directly is given below:
 Here, a new keyword is used to create an instance of an array.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
JavaScript array constructor (new keyword)
• Here, you need to create an instance of an array by passing arguments in the
constructor
<script>
var emp=new Array("Jai",“lava",“kusa");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
• Changing an Array Element
cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
• Converting an Array to a String
• The JavaScript method toString() converts an array to a string of (comma-separated) array
values.
fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
• Arrays are Objects
• Arrays are a special type of objects. The type of operator in JavaScript returns "object"
for arrays.
• But, JavaScript arrays are best described as arrays.
• Arrays use numbers to access their "elements". In this example, person[0] returns
John:object
• person = {firstName:"John", lastName:"Doe", age:46};
• Accessing the First Array Element
fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];
• Accessing the Last Array Element
let fruit = fruits[fruits.length - 1];
• Adding Array Elements
• The easiest way to add a new element to an array is using the push() method:
fruits.push("Lemon");
• A new element can also be added to an array using the length property:
fruits[fruits.length] = "Lemon";
• Associative Arrays
• Many programming languages support arrays with named indexes.
• Arrays with named indexes are called associative arrays (or hashes).
• JavaScript does not support arrays with named indexes.
• In JavaScript, arrays always use numbered indexes.
person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
• How to Recognize an Array
• A common question is: How do I know if a variable is an array?
• The problem is that the JavaScript operator typeof returns "object":
const fruits = ["Banana", "Orange", "Apple"];
let type = typeof fruits; //object
• To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method
Array.isArray():
Array.isArray(fruits); //true
• The instanceof operator returns true if an object is created by a given constructor:
fruits instanceof Array; //true
Array Properties
• Constructor Returns the function that created the Array object's
prototype
• Length Sets or returns the number of elements in an array
• Prototype Allows you to add properties and methods to an Array
object
Array Methods
 concat() Joins two or more arrays and returns a copy of the joined arrays
 copyWithin() Copies array elements within the array, to and from specified
positions
 every() Check if every element in an array passes a test
 fill() Fill the elements in an array with a static value
 filter() Creates a new array with every element in an array that passes a test
 find() Returns the value of the first element in an array that passes a test
 findIndex() Returns the index of the first element in an array that passes a test
 forEach() Calls a function for each array element
Cont…
 indexOf() Search the array for an element and returns its position
 isArray() Checks whether an object is an array
 join() Joins all elements of an array into a string
 lastIndexOf() Search the array for an element, starting at the end, and returns its
position
 map() Creates a new array with the result of calling a function for each array
element
 pop() Removes the last element of an array and returns that element
 push() Adds new elements to the end of an array and returns the new length
• sort() Sorts the elements of an array
• splice() Adds/Removes elements from an array
Cont…
 reduce() Reduce the values of an array to a single value (going left-to-right)
 reduceRight() Reduce the values of an array to a single value (going right-to-left)
 reverse() Reverses the order of the elements in an array
 shift() Removes the first element of an array, and returns that element
 slice() Selects a part of an array, and returns the new array
 some() Checks if any of the elements in an array pass a test
• toString() Converts an array to a string and returns the result
• unshift() Adds new elements to the beginning of an array, and returns the new
length
• valueOf() Returns the primitive value of an array
JavaScript Math Object
• The JavaScript Math object allows you to perform mathematical tasks
on numbers.
• Unlike other objects, the Math object has no constructor.
• The Math object is static.
• All methods and properties can be used without creating a Math
object first.
Math Properties (Constants)
• Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
<html> </script>
<body> </body>
<h2>JavaScript Math Constants</h2> </html>
<p id="demo"></p>
<script> Output:
document.getElementById("demo").innerHTML = JavaScript Math Constants
"<p><b>Math.E:</b> " + Math.E + "</p>" + Math.E: 2.718281828459045
"<p><b>Math.PI:</b> " + Math.PI + "</p>" + Math.PI: 3.141592653589793
"<p><b>Math.SQRT2:</b> " + Math.SQRT2 + "</p>" + Math.SQRT2: 1.4142135623730951
"<p><b>Math.SQRT1_2:</b> " + Math.SQRT1_2 + Math.SQRT1_2: 0.7071067811865476
"</p>" + Math.LN2: 0.6931471805599453
"<p><b>Math.LN2:</b> " + Math.LN2 + "</p>" +
Math.LN10: 2.302585092994046
"<p><b>Math.LN10:</b> " + Math.LN10 + "</p>" + Math.LOG2E: 1.4426950408889634
"<p><b>Math.LOG2E:</b> " + Math.LOG2E + "</p>" Math.Log10E: 0.4342944819032518
+
"<p><b>Math.Log10E:</b> " + Math.LOG10E +
"</p>";
Math Methods
• Number to Integer
• There are 4 common methods to round a number to an integer:
Math.round(x) Returns x rounded to its nearest integer

Math.ceil(x) Returns x rounded up to its nearest integer

Math.floor(x) Returns x rounded down to its nearest integer

Math.trunc(x) Returns the integer part of x (new in ES6)


• Math.round()
• Math.round(x) returns the nearest integer:
• Math.round(4.6); //5
• Math.ceil()
• Math.ceil(x) returns the value of x rounded up to its nearest integer:
• Math.ceil(4.9); //5
• Math.floor()
• Math.floor(x) returns the value of x rounded down to its nearest
integer:
• Math.floor(4.9); //4
• Math.trunc()
• Math.trunc(x) returns the integer part of x:
• Math.trunc(4.9); //4
 Math.random()
 Math.random() returns a random number between 0 (inclusive), and 1
(exclusive):
 Math.random();
• Math.sign()
• Math.sign(x) returns if x is negative, null or positive:
• Math.sign(-4); //-1
• Math.pow()
• Math.pow(x, y) returns the value of x to the power of y:
• Math.pow(8, 2); //64
• Math.sqrt()
• Math.sqrt(x) returns the square root of x:
• Math.sqrt(64); //8
• Math.abs()
• Math.abs(x) returns the absolute (positive) value of x:
• Math.abs(-4.7); //4.7
 Math.min() and Math.max()
 Math.min() and Math.max() can be used to find the lowest or highest value in a list of
arguments:
 Math.min(0, 150, 30, 20, -8, -200); //-200
 Math.max(0, 150, 30, 20, -8, -200); //150
 The Math.log() Method
 Math.log(x) returns the natural logarithm of x.
 Math.log(1); //0
 The Math.log2() Method
 Math.log2(x) returns the base 2 logarithm of x.
 Math.log2(8); //3
 The Math.log10() Method
 Math.log10(x) returns the base 10 logarithm of x.
 Math.log10(1000); //3
 Math.sin()
 Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in
radians).
 Math.sin(90 * Math.PI / 180); // returns 1 (the sine of 90 degrees)
 Math.cos()
 Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in
radians).
 Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0 degrees)
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
acosh(x) Returns the hyperbolic arccosine of x
asin(x) Returns the arcsine of x, in radians
asinh(x) Returns the hyperbolic arcsine of x
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians

atan2(y, x) Returns the arctangent of the quotient of its arguments


atanh(x) Returns the hyperbolic arctangent of x
cbrt(x) Returns the cubic root of x
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
cosh(x) Returns the hyperbolic cosine of x
x
exp(x) Returns the value of E
floor(x) Returns x, rounded downwards to the nearest integer

log(x) Returns the natural logarithm (base E) of x

max(x, y, z, ..., n) Returns the number with the highest value

min(x, y, z, ..., n) Returns the number with the lowest value

pow(x, y) Returns the value of x to the power of y


random() Returns a random number between 0 and 1

round(x) Rounds x to the nearest integer


sign(x) Returns if x is negative, null or positive (-1, 0, 1)

sin(x) Returns the sine of x (x is in radians)


sinh(x) Returns the hyperbolic sine of x
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
tanh(x) Returns the hyperbolic tangent of a number

trunc(x) Returns the integer part of a number (x)


JavaScript Date Objects
• By default, JavaScript will use the browser's time zone and display a
date as a full text string:
• Creating Date Objects
• Date objects are created with the new Date() constructor.
• new Date()
• new Date(year, month, day, hours, minutes, seconds, milliseconds)
• new Date(milliseconds)
• new Date(date string)
 new Date()
 new Date() creates a new date object with the current date and time:
const d = new Date();
 new Date(year, month, ...)
 new Date(year, month, ...) creates a new date object with a specified date and time.
 7 numbers specify year, month, day, hour, minute, second, and millisecond (in that
order):
const d = new Date(2018, 11, 24, 10, 33, 30, 0);
 5 numbers specify year, month, day, hour, and minute:
const d = new Date(2018, 11, 24, 10, 33);
 3 numbers specify year, month, and day:
const d = new Date(2018, 11, 24);
 One and two digit years will be interpreted as 19xx:
const d = new Date(99, 11, 24);
 new Date(dateString)
 new Date(dateString) creates a new date object from a date string:
const d = new Date("October 13, 2014 11:13:00");
 When you display a date object in HTML, it is automatically converted to a string, with
the toString() method.
const d = new Date();
d.toString();
JavaScript String Object
 JavaScript strings are for storing and manipulating text.
 A JavaScript string is zero or more characters written inside quotes.
let text = "John Doe";
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes
 String Length
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p id="demo"></p>
<script>
// x is a string
let x = "John";
// y is an object
let y = new String("John");
document.getElementById("demo").innerHTML =
typeof x + "<br>" + typeof y;
</script>
</body>
</html>
Output:
JavaScript Strings
string
object
String Methods and Properties
• JavaScript String Length
• The length property returns the length of a string:
let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = txt.length;
• Extracting String Parts
• There are 3 methods for extracting a part of a string:
• slice(start, end)
• substring(start, end)
• substr(start, length)
• JavaScript String slice()
• slice() extracts a part of a string and returns the extracted part in a new string.
• The method takes 2 parameters: the start position, and the end position (end not included).
• This example slices out a portion of a string from position 7 to position 12 (13-1):
• let str = "Apple, Banana, Kiwi";
let part = str.slice(7, 13);
 JavaScript String substring()
 The difference is that substring() cannot accept negative indexes.
 let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
 JavaScript String substr()
 substr() is similar to slice().
 The difference is that the second parameter specifies the length of the extracted part.
 let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
 If you omit the second parameter, substr() will slice out the rest of the string.
• Replacing String Content
• The replace() method replaces a specified value with another value in a string:
• let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
• let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace(/Microsoft/g, "W3Schools");
 Converting to Upper and Lower Case
 A string is converted to upper case with toUpperCase():
 A string is converted to lower case with toLowerCase():
 let text1 = "Hello World!";
let text2 = text1.toUpperCase();
 let text1 = "Hello World!"; // String
let text2 = text1.toLowerCase(); // text2 is text1 converted to lower
 JavaScript String concat()
 concat() joins two or more strings:
 let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
 JavaScript String trim()
 The trim() method removes whitespace from both sides of a string:
 let text1 = " Hello World! ";
let text2 = text1.trim();
 JavaScript String charAt()
 The charAt() method returns the character at a specified index (position) in a string:
 let text = "HELLO WORLD";
let char = text.charAt(0);
 JavaScript String charCodeAt()
 The charCodeAt() method returns the unicode of the character at a specified index in a
string:
 The method returns a UTF-16 code (an integer between 0 and 65535).
 let text = "HELLO WORLD";
let char = text.charCodeAt(0);
 JavaScript String split()
 A string can be converted to an array with the split() method:
 text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe
JavaScript Search Methods
 String indexOf()
 String lastIndexOf()
 String startsWith()
 String endsWith()
 JavaScript String indexOf()
 The indexOf() method returns the index of (the position of)
the first occurrence of a specified text in a string:
 let str = "Please locate where 'locate' occurs!";
str.indexOf("locate");
 JavaScript String lastIndexOf()
 The lastIndexOf() method returns the index of the last occurrence of
a specified text in a string:
 let str = "Please locate where 'locate' occurs!";
str.lastIndexOf("locate");
 JavaScript String search()
 The search() method searches a string for a specified value and
returns the position of the match:
 let str = "Please locate where 'locate' occurs!";
str.search("locate");
 JavaScript String match()
 The match() method searches a string for a match against a regular expression,
and returns the matches, as an Array object.
 Search a string for "ain":
 let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/g);
 JavaScript String includes()
 The includes() method returns true if a string contains a specified value.
 let text = "Hello world, welcome to the universe.";
text.includes("world");
JavaScript HTML DOM
 With the HTML DOM, JavaScript can access and change all the elements of an
HTML document.
 DOM (Document Object Model)
 When a web page is loaded, the browser creates a Document Object Model of
the page.
 The DOM is an application programming interface(API) that defines an interface
between HTML documents and application programs
 The DOM specification consists of a collection of interfaces
• The HTML DOM model is constructed as a tree of Objects:
 With the object model, JavaScript gets all the power it needs to create dynamic
HTML:
 JavaScript can change all the HTML elements on the page
 JavaScript can change all the HTML attributes on the page
 JavaScript can change all the CSS styles on the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events on the page
 JavaScript can create new HTML events on the page
What is the DOM?
 The DOM is a W3C (World Wide Web Consortium) standard.
 The DOM defines a standard for accessing documents:
 "The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."
 The W3C DOM standard is separated into 3 different parts:
 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents
What is the HTML DOM?
 The HTML DOM is a standard object model and programming interface for
HTML. It defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
 In other words: The HTML DOM is a standard for how to get, change, add, or
delete HTML elements.
The HTML DOM Document Object
 The document object represents your web page.
 If you want to access any element in an HTML page, you always start with
accessing the document object.
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name


Changing HTML Elements
• element.innerHTML = new html content
• Change the inner HTML of an element
• element.attribute = new value
• Change the attribute value of an HTML element
• element.setAttribute(attribute, value)
• Change the attribute value of an HTML element
• element.style.property = new style
• Change the style of an HTML element
Event-driven Computation
• HTML events are "things" that happen to HTML elements
• An HTML event can be something the browser does, or something a user does.
• Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
 Syntax:
 <element event='some JavaScript'>
 <element event="some JavaScript">
<!DOCTYPE html>
<html>
<body>
<button onclick="document.getElementById('demo').innerHTML=Date()">
The time is?</button>
<p id="demo"></p>
</body>
</html>
Common HTML Events
Event Description
onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

onsubmit The submit button is pressed


onfocus The element receive the input focus
onblur The element loses the input focus

ondbclick The user double click the left mouse button


JavaScript Window Navigator
 The window.navigator object contains information about the visitor's browser.
 The window.navigator object can be written without the window prefix.
 Some examples:
 navigator.appName
 navigator.appCodeName
 navigator.platform
• The cookieEnabled property returns true if cookies are enabled, otherwise false:
• The appName property returns the application name of the browser:
• The appCodeName property returns the application code name of the browser:
• The appVersion property returns version information about the browser:
• The userAgent property returns the user-agent header sent by the browser to the
server:
• The language property returns the browser's language:
• The onLine property returns true if the browser is online:
• The javaEnabled() method returns true if Java is enabled:
• The platform property returns the browser platform (operating system):
Browser Application Name
<!DOCTYPE html>
<html>
<body>
<h2>The Navigator Object</h2>
<p>The appName property returns the application name of the browser:</p>
<p id="demo"></p>
<p>Strange enough, "Netscape" is the application name for both IE11, Chrome, Firefox,
and Safari.</p>
<script>
document.getElementById("demo").innerHTML =
"navigator.appName is " + navigator.appName;
</script>
</body>
</html>
Dynamic Documents with Javascripts
• Positions the elements
• Moving Elements
• Element Visibility
• Changing Colors and Fonts
• Dynamic Contents
• Locating and Mouse Cursor
• Slow Movement of Element
• Dragging and Dropping Elements
Positioning Elements
 The position property specifies the type of positioning method used for an element
(static, relative, fixed, absolute or sticky).
 HTML elements are positioned static by default.
 An element with position: relative; is positioned relative to its normal position.
 An element with position: fixed; is positioned relative to the viewport, which means it
always stays in the same place even if the page is scrolled. The top, right, bottom, and
left properties are used to position the element.
• An element with position: absolute; is positioned relative to the nearest positioned
ancestor (instead of positioned relative to the viewport, like fixed).
• An element with position: sticky; is positioned based on the user's scroll position.

Example: https://www.geeksforgeeks.org/css-positioning-elements/
Regular Expression
• A regular expression is an object that describes a pattern of characters.
• Regular expressions are used to perform pattern-matching and "search-and-replace"
functions on text.
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;
Ex:
var patt = /gitam/i
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)
m Perform multiline matching
d Perform start and end matching (New in ES2022)
Regular Expression Patterns:
• Brackets are used to find a range of characters:
• Metacharacters are characters with a special meaning

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 |
[^abc] Find any character, not inside the brackets
[^0-9] Find any digit not in between the brackets
Metacharacter Description
\. Search single characters, except line terminator or newline.
\w Find the word character i.e. characters from a to z, A to Z, 0 to 9
\d Find a digit
\D Search non-digit characters i.e all the characters except digits
\s Find a whitespace character
\S Find the non-whitespace characters.
\b Find a match at the beginning or at the end of a word
\B Find a match that is not present at the beginning or end of a word.
\0 Find the NULL character.
\n Find the newline character.
\f Find the form feed character
\r Find the carriage return character
\t Find the tab character
\v Find the vertical tab character
\uxxxx Find the Unicode character specified by the hexadecimal number xxxxx
• Quantifiers define quantities:

Quantifier Description

n+ Match any string that contains at least one n

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

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

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

m{X, Y} Find the match of any string that contains a sequence of m, X to Y times

m{X,} Find the match of any string that contains a sequence of m, at least X times

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

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

?!m Find the match of any string which is not followed by a specific string m.
Regular Expression Object Methods:

Method Description

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

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

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

toString() Return the string value of the regular expression


Using the RegExp Object:
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!");
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!");
// input string
let str = "Visit geeksforGeeks!";
// searching string with modifier i
let n = str.search(/GeeksforGeeks/i);
console.log(n);
// searching string without modifier i
let n = str.search(/GeeksforGeeks/);
console.log(n);
output:6 -1
// input string
let str = "Please visit gfG!";
// replacing with modifier i
let txt = str.replace(/gfg/i, "geeksforgeeks");
console.log(txt);
output: Please visit geeksforgeeks!
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Regular Expression</h1>
<p id="demo"></p> Output:
W3Schools
<script> W3Schools
let text = "Visit W3Schools"; null
let pattern = /w3schools/i; W3Schools
Visit geeksforgeeks
let result = text.match(pattern);
let res=pattern.exec(text)
let res1=/w3schools/.exec(text)
let res2=/W3Schools/.exec(text)
let txt = text.replace(pattern, "geeksforgeeks");
document.getElementById("demo").innerHTML = result + "<br>"+ res +"<br>"+ res1 +"<br>"+res2 +"<br>"+txt;
</script>
</body>
</html>
JavaScript Form Validation:
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
} }
</script>
<body>
<form name="myform" method="post" action="" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
JavaScript Number Validation:
<html>
<head>
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}}
</script>
</head>
<body>
<form name="myform" action="" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
JavaScript email validation:
• email id must contain the @ and . character
• There must be at least one character before and after the @.
• There must be at least two characters after . (dot).
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
//m.c@gmail.com
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
} }
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy