0% found this document useful (0 votes)
10 views119 pages

JavaScript Basics and Key Features

This document provides an overview of JavaScript, highlighting its importance as a programming language for web development alongside HTML and CSS. It covers key features, such as client-side scripting, event-driven programming, and the use of functions and arrays. Additionally, it discusses how to create and manipulate JavaScript code within HTML, including the use of external scripts and various methods for displaying output.

Uploaded by

sharaj55345
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)
10 views119 pages

JavaScript Basics and Key Features

This document provides an overview of JavaScript, highlighting its importance as a programming language for web development alongside HTML and CSS. It covers key features, such as client-side scripting, event-driven programming, and the use of functions and arrays. Additionally, it discusses how to create and manipulate JavaScript code within HTML, including the use of external scripts and various methods for displaying output.

Uploaded by

sharaj55345
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

Unit 3: Java Script

JavaScript Basics –Functions – Arrays – DOM - Built-in Objects –


Regular Expression - Event handling – Validation
Dr. Adyasha Sahu
JavaScript Basics
• JavaScript is the world's most popular programming language.
• JavaScript is the programming language of the Web.
• JavaScript is a versatile, high-level, interpreted programming language
primarily known for enabling interactive and dynamic content on web
pages. It is a cornerstone of modern web development, alongside
HTML for structure and CSS for styling.
JavaScript Basics
• Why Study JavaScript?
• JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
JavaScript Basics
Key Features of JavaScript
• Here are some key features of JavaScript that make it a powerful language for web
development:
• Client-Side Scripting:JavaScript runs on the user's browser, so has a faster response time
without needing to communicate with the server.
• Versatile: JavaScript can be used for a wide range of tasks, from simple calculations to
complex server-side applications.
• Event-Driven: JavaScript can respond to user actions (clicks, keystrokes) in real-time.
• Asynchronous: JavaScript can handle tasks like fetching data from servers without
freezing the user interface.
• Rich Ecosystem: There are numerous libraries and frameworks built on JavaScript, such
as React, Angular, and [Link], which make development faster and more efficient.
JavaScript Basics
• The <script> Tag
• In HTML, JavaScript code is inserted between <script> and </script> tags.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript in Body</h2>

<p id="demo"></p> Output:


<script>
[Link]("demo").innerHTML = "My First JavaScript";
</script>

</body>
</html>
JavaScript Basics
JavaScript in <head> or <body>
• You can place any number of scripts in an HTML document.
• Scripts can be placed in the <body>, or in the <head> section
of an HTML page, or in both.
JavaScript Basics
JavaScript Functions and Events:
• A JavaScript function is a block of JavaScript code, that can be executed when
"called" for.
• For example, a function can be called when an event occurs, like when the user
clicks a button.
• A JavaScript function is a block of JavaScript code, that can be executed when
"called" for. For example, a function can be called when an event occurs, like
when the user clicks a button.
JavaScript Basics
JavaScript in <head>
• In this example, a JavaScript function is placed in
the <head> section of an HTML page.
• The function is invoked (called) when a button is clicked:
JavaScript Basics
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
} Output:
</script>
</head>
<body>

<h2>Demo JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>
JavaScript Basics
JavaScript in <body>
• In this example, a JavaScript function is placed in
the <body> section of an HTML page.
• The function is invoked (called) when a button is clicked:
JavaScript Basics

Output:
JavaScript Basics
External JavaScript:
• Scripts can also be placed in external files:

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

• An external script reference can be placed in <head> or <body> as user likes.


• The script will behave as if it was located exactly where the <script> tag is located.
• External scripts cannot contain <script> tags.
JavaScript Basics
External JavaScript Advantages
 Placing scripts in external files has some advantages:
 It separates HTML and code
 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads
 To add several script files to one page - use several script tags:
• An external script can be referenced in 3 different ways:
• With a full URL (a full web address):
• With a file path (like /js/):
• Without any path:
JavaScript Output

• JavaScript Display Possibilities


• JavaScript can "display" data in different ways:
• Writing into an HTML element, using innerHTML.
• Writing into the HTML output using [Link]().
• Writing into an alert box, using [Link]().
• Writing into the browser console, using [Link]().
Using innerHTML

Using innerHTML:

• To access an HTML element, JavaScript can use the


[Link](id) method.
• The id attribute defines the HTML element.
• The innerHTML property defines the HTML content.
Using innerHTML
EXAMPLE:
<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>


<p>My First Paragraph.</p> Output:

<p id="demo"></p>

<script>
[Link]("demo").innerHTML = 5 + 6;
</script>

</body>
</html>
Using [Link]
EXAMPLE #1:
<!DOCTYPE html>
<html>
<body>
Output:
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Using [Link]
EXAMPLE #2:
<!DOCTYPE html>
<html>
<body> Output:

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button type="button" onclick="[Link](5 + 6)">Try it</button>

</body>
</html>
Using [Link]
EXAMPLE #1:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Using [Link]
EXAMPLE #2:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
alert(5 + 6);
</script>
</body>
</html>
Using [Link]
EXAMPLE #1:
• <!DOCTYPE html>
<html>
<body>

<script>
[Link](5 + 6);
</script>

</body>
</html>
Javascript Print

• JavaScript does not have any print object or print methods.


• You cannot access output devices from JavaScript.
• The only exception is that you can call
the [Link]() method in the browser to print the
content of the current window.
Javascript Print

• <!DOCTYPE html>
<html>
<body>

<button onclick="[Link]()">Print this page</button>

</body>
</html>
Statement
• A computer program is a list of "instructions" to be "executed" by a computer.
• In a programming language, these programming instructions are called statements.
• A JavaScript program is a list of programming statements.
• JavaScript statements are composed of:
• Values, Operators, Expressions, Keywords, and Comments.
• This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":
• Example: [Link]("demo").innerHTML = "Hello Dolly.";
• Most JavaScript programs contain many JavaScript statements.
• The statements are executed, one by one, in the same order as they are written.
Statement
Semicolons (;)
• Semicolons separate JavaScript statements.
• Add a semicolon at the end of each executable statement. When separated by semicolons,
multiple statements on one line are allowed.
White Space
• JavaScript ignores multiple spaces. You can add white space to your script to make it more
readable.
Line Length and Line Breaks
• For best readability, programmers often like to avoid code lines longer than 80 characters.
• If a JavaScript statement does not fit on one line, the best place to break it is after an operator
Code Blocks
• JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
• The purpose of code blocks is to define statements to be executed together.
• One place you will find statements grouped together in blocks, is in JavaScript functions
JavaScript Keywords
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be
executed on a condition
switch Marks a block of statements to be
executed in different cases
for Marks a block of statements to be
executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of
statements
JavaScript Values
JavaScript Values:

The JavaScript syntax defines two types of values:


•Fixed values: Fixed values are called Literals.
•Variable values: Variable values are called Variables.
JavaScript Literals
The two most important syntax rules for fixed values are:
i. Numbers are written with or without decimals
ii. Strings are text, written within double or single quotes
JavaScript Variables
• In a programming language, variables are used to store data values.
• JavaScript uses the keywords var, let and const to declare variables.
• An equal sign is used to assign values to variables.
• In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
eg. let x;
x = 6;
JavaScript Variables
• Variables are Containers for Storing Data
• JavaScript Variables can be declared in 4 ways:
 Automatically
 Using var
 Using let
 Using const
JavaScript Variables
1. Automatically:
• In this first example, x, y, and z are undeclared variables.
• They are automatically declared when first used:

Output:
JavaScript Variables
2. Using Var:
• The var keyword was used in all JavaScript code from 1995 to 2015.
• The let and const keywords were added to JavaScript in 2015.
• The var keyword should only be used in code written for older browsers.

Output:
JavaScript Variables
3. Using let:

Output:
JavaScript Variables
4. Using const:

Output:
JavaScript Variables
When to Use var, let, or const?
• Always declare variables
• Always use const if the value should not be changed
• Always use const if the type should not be changed (Arrays and Objects)
• Only use let if you can't use const
• Only use var if you MUST support old browsers.
JavaScript Identifiers
• All JavaScript variables must be identified with unique names. These unique names are
called identifiers.
• Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
• The general rules for constructing names for variables (unique identifiers) are:
 Names can contain letters, digits, underscores, and dollar signs.
 Names must begin with a letter.
 Names can also begin with $ and _ (but we will not use it in this tutorial).
 Names are case sensitive (y and Y are different variables).
 Reserved words (like JavaScript keywords) cannot be used as names.
• JavaScript identifiers are case-sensitive.
JavaScript Functions
• Functions are fundamental building blocks in all programming.
• Functions enable better code organization, modularity, and efficiency.
• Functions are reusable block of code designed to perform a particular task.
• Functions execute when they are "called" or "invoked".

JavaScript Function Syntax

• A function is defined with the function keyword, followed by the function name, followed by
parentheses ( ), followed by brackets { }.
• The name follows the naming rules for variables (letters, digits, ...).
• Optional parameters are listed inside parentheses: (p1, p2, p3)
• The code to be executed is listed inside curly brackets: { code }
• Functions can optionally return a value back to the "caller".
JavaScript Functions
Why Functions: Advantages
• With functions you can reuse code
• You can write code that can be used many times.
• You can use the same code with different arguments, to produce different results.
JavaScript Functions
Function Invocation ():
The code inside the function will execute when "something" invokes (calls) the function:
• When it is invoked (called) from JavaScript code
• When an event occurs (a user clicks a button)
• Automatically (self invoked)
• The () operator invokes (calls) the function
Example:

Output:
Arrow Functions

Output: Output:
JavaScript Functions
Local Variables:
• Variables declared within a JavaScript function, become LOCAL to the function.
• Local variables can only be accessed from within the function.
• Since local variables are only recognized inside their functions, variables with the same name can be used in
different functions.
• Local variables are created when a function starts, and deleted when the function is completed.

Parameters vs. Arguments:


• In JavaScript, function parameters and arguments are distinct concepts:
• Parameters are the names listed in the function definition.
• Parameters are the names of the values that will be passed.

• "name" and "age" are parameters


• Arguments are the values passed to the function when it is invoked or called.
• Arguments are the values received by the function.
• Example: "John" and 21 are arguments
JavaScript Array

In JavaScript, an array is an ordered list of


values. Each value is called an element
specified by an index. An Array is an object
type designed for storing data collections.
JavaScript Array
Key characteristics of JavaScript arrays are:
• Elements: An array is a list of values, known as elements.
• Ordered: Array elements are ordered based on their index.
• Zero indexed: The first element is at index 0, the second at index 1, and so on.
• Dynamic size: Arrays can grow or shrink as elements are added or removed.
• Heterogeneous: Arrays can store elements of different data types (numbers,
strings, objects and other arrays).
JavaScript Array
Creating JavaScript arrays:
• The array literal form uses the square brackets [] to wrap a comma-separated list
of elements.
let arrayName = [element1, element2, element3, ...];
• Array literal form uses the square brackets [] to wrap a comma-separated list of
elements.
• The following example creates the colors array that holds string elements:
let colors = ['red', 'green', 'blue'];
• To create an empty array, you use square brackets without specifying any element
like this:
let emptyArray = [];
Creating JavaScript arrays:
JavaScript Array
• Spaces and line breaks are not important. A declaration can span multiple lines.
const cars =
"Saab",
"Volvo",
"BMW"
];
• You can also create an empty array, and provide elements later:
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
• The JavaScript method toString() converts an array to a string of (comma separated) array values.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("demo").innerHTML = [Link]();
• With JavaScript, the full array can be accessed by referring to the array name.
const cars = ["Saab", "Volvo", "BMW"];
[Link]("demo").innerHTML = cars;
JavaScript Array
Accessing Array Elements
• JavaScript arrays are zero-based indexed. In other words, the first element of an array starts at
index 0, the second element starts at index 1, and so on.
• To access an element in an array, you specify an index in the square brackets []
eg. arrayName[index]

Output:
JavaScript Array
Array Size:

• The length property of an array returns the length of an array (the number of array
elements).
• The following example shows how to use the length property:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = [Link];
Basic operations on arrays
• The following explains some basic operations on
arrays. And you’ll learn advanced operations such
as map(), filter(), and reduce() in the next tutorials.
• 1) Adding an element to the end of an array
• To add an element to the end of an array, you use
the push() method:

let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
[Link]('Red Sea');
[Link](seas);
[ 'Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea', 'Red Sea' ]
JavaScript Array
2) Adding an element to the beginning of an array
• To add an element to the beginning of an array, you
use the unshift() method:

let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
[Link]('Red Sea');
[Link](seas);

[ 'Red Sea', 'Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea' ]
JavaScript Array
• Removing an element from the end of an array
• To remove an element from the end of an array, you
use the pop() method:

let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
const lastElement = [Link]();
[Link](lastElement);

Baltic Sea
JavaScript Array
• Removing an element from the beginning of an array
• To remove an element from the beginning of an array,
you use the shift() method:

let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea']; const
firstElement = [Link]();
[Link](firstElement);

Black Sea
JavaScript Array
• Finding an index of an element in the array
• To find the index of an element, you use the indexOf()
method:

let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
let index = [Link]('North Sea');
[Link](index); // 2
Summary
• In JavaScript, an array is an order list of values. Each value is called an
element specified by an index.
• An array can hold values of mixed types.
• JavaScript arrays are dynamic, which mean that they grow or shrink as
needed.
DOM
• Every web page resides inside a browser window which can be
considered as an object.
• A Document object represents the HTML document that is displayed
in that window. The Document object has various properties that
refer to other objects which allow access to and modification of
document content.
• The way a document content is accessed and modified is called
the Document Object Model, or DOM.
• The Objects are organized in a hierarchy. This hierarchical structure
applies to the organization of objects in a Web document.
• Window object − Top of the hierarchy. It is the outmost element of the object
hierarchy.
• Document object − Each HTML document that gets loaded into a window
becomes a document object. The document contains the contents of the
page.
• Form object − Everything enclosed in the <form>...</form> tags sets the form
object.
• Form control elements − The form object contains all the elements defined
for that object such as text fields, buttons, radio buttons, and checkboxes.
This hierarchical structure applies to the organization of objects in a
Web document.
• There are several DOMs in existence. The following sections explain each of
these DOMs in detail and describe how you can use them to access and
modify document content.
• The Legacy DOM − This is the model which was introduced in early versions of
JavaScript language. It is well supported by all browsers, but allows access only to
certain key portions of documents, such as forms, form elements, and images.
• The W3C DOM − This document object model allows access and modification of all
document content and is standardized by the World Wide Web Consortium (W3C).
This model is supported by almost all the modern browsers.
• The IE4 DOM − This document object model was introduced in Version 4 of
Microsoft's Internet Explorer browser. IE 5 and later versions include support for
most basic W3C DOM features.
The Legacy DOM

• This is the model which was introduced in early versions of JavaScript


language. It is well supported by all browsers, but allows access only
to certain key portions of documents, such as forms, form elements,
and images.
• This model provides several read-only properties, such as title, URL,
and lastModified provide information about the document as a
whole. Apart from that, there are various methods provided by this
model which can be used to set and get document property values.
Document Properties in Legacy DOM
Example
• We can locate any HTML element within any HTML document
using HTML DOM. For instance, if a web document contains
a form element then using JavaScript we can refer to it
as [Link][0]. If your Web document includes
two form elements the first form is referred to as
[Link][0] and the second [Link][1].
• Using the hierarchy and properties given above, we can access
the first form element
using [Link][0].elements[0] and so on.
• <body>
• <html>
• <h1 id = "title">This is main title</h1>

• <p>Click the following to see the result:</p>
• <head>

• <title> Document Title </title>
• <form name = "FirstForm">

• <input type = "button" value = "Click Me" onclick =
• <script type = "text/javascript"> "myFunc();" />

• <!-- • <input type = "button" value="Cancel">


• function myFunc() { • </form>
• var ret = [Link]; •

• alert("Document Title : " + ret ); • <form name = "SecondForm">


• • <input type = "button" value = "Don't ClickMe"/>
• var ret = [Link]; • </form>
• alert("Document URL : " + ret ); •
• • </body>
• var ret = [Link][0]; • </html>

• alert("Document First Form : " + ret );



• var ret = [Link][0].elements[1];
• alert("Second element : " + ret );
• }
• //-->
• </script>

• </head>
The W3C DOM

• This document object model allows access and modification of all


document content and is standardized by the World Wide Web
Consortium (W3C). This model is supported by almost all the modern
browsers.
• The W3C DOM standardizes most of the features of the legacy DOM
and adds new ones as well. In addition to supporting forms[ ],
images[ ], and other array properties of the Document object, it
defines methods that allow scripts to access and manipulate any
document element and not just special-purpose elements like forms
and images.
Document Methods in W3C DOM
Example

• This is very easy to manipulate ( Accessing and Setting ) document


element using W3C DOM. You can use any of the methods
like getElementById, getElementsByName,
or getElementsByTagName.
HTML DOM Document getElementById()
• The getElementById() method returns an element with a specified value.
• The getElementById() method returns null if the element does not exist.
• The getElementById() method is one of the most common methods in the HTML
DOM. It is used almost every time you want to read or edit an HTML element.
• Example:

Output:
HTML DOM Document getElementByName()

• The getElementsByName() method returns a collection of elements


with a specified name.
• The getElementsByName() method returns a live NodeList.

NodeList:
• A NodeList is an array-like collection (list) of nodes.
• The nodes in the list can be accessed by index. The index starts at 0.
• The length Poperty returns the number of nodes in the list.
HTML DOM Document getElementByName()

Example:

Output:
HTML DOM Document getElementByTagName()

• The getElementsByTagName() method returns a collection of all


elements with a specified tag name.
• The getElementsByTagName() method returns an HTMLCollection.
• The getElementsByTagName() property is read-only.
• getElementsByTagName("*") returns all elements in the document.

HTMLCollection

• An HTMLCollection is an array-like collection (list) of HTML elements.


• The length Property returns the number of elements in the collection.
• The elements can be accessed by index (starts at 0).
• An HTMLCollection is live. It is automatically updated when the document is
changed.
HTML DOM Document getElementByName()

Example:

Output:
• <html> • <body>
• • <h1 id = "heading">This is main title</h1>
• <head> • <p>Click the following to see the
result:</p>
• <title> Document Title </title>


• <form id = "form1" name = "FirstForm">
• <script type = "text/javascript">
• <input type = "button" value = "Click Me"
• <!-- onclick = "myFunc();" />
• function myFunc() { • <input type = "button" value = "Cancel">
• var ret = • </form>
[Link]("title");

• alert("Document Title : " + ret[0].text
); • <form d = "form2" name = "SecondForm">
• • <input type = "button" value = "Don't
ClickMe"/>
• var ret =
[Link]("heading"); • </form>
• alert([Link] ); •
• } • </body>
• //--> • </html>
• </script>

• </head>
The IE 4 DOM

• This document object model was introduced in Version 4 of


Microsoft's Internet Explorer browser. IE 5 and later versions include
support for most basic W3C DOM features.
Document Properties in IE 4 DOM
Document Methods in IE4 DOM
Example
• The IE 4 DOM does not support the getElementById() method.
Instead, it allows you to look up arbitrary document elements by id
attribute within the all [] array of the document object.
• Here's how to find all <li> tags within the first <ul> tag. Note that you
must specify the desired HTML tag name in uppercase with
the [Link]( ) method.
Example
• The IE 4 DOM does not support the getElementById() method.
Instead, it allows you to look up arbitrary document elements by id
attribute within the all [] array of the document object.
• Here's how to find all <li> tags within the first <ul> tag. Note that you
must specify the desired HTML tag name in uppercase with
the [Link]( ) method.
• var lists = [Link]("UL");
• var items = lists[0].[Link]("LI");
Example
• <html> • <body>
• • <h1 id = "heading">This is main title</h1>
• <head> • <p>Click the following to see the result:</p>
• <title> Document Title </title> •
• • <form id = "form1" name = "FirstForm">
• <script type = "text/javascript"> • <input type = "button" value = "Click Me" onclick = "myFunc();" />
• <!-- • <input type = "button" value = "Cancel">
• function myFunc() { • </form>
• var ret = [Link]["heading"]; •
• alert("Document Heading : " + [Link] ); • <form d = "form2" name = "SecondForm">
• • <input type = "button" value = "Don't ClickMe"/>
• var ret = [Link]("P");; • </form>
• alert("First Paragraph : " + ret[0].innerHTML); •
• } • </body>
• //--> • </html>
• </script>

• </head>
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript

Output:
Built-in objects in JavaScript
Built-in objects in JavaScript
Built-in objects in JavaScript

7. Array Object
Built-in objects in JavaScript
Regular Expression
Regular Expression

• A Regular Expression is a sequence of characters that


forms a search pattern.
• Regex is a common shorthand for a regular expression.
• JavaScript RexExp is an Object for handling Regular
Expressions.
• RegExp are be used for:
 Text searching
 Text replacing
 Text validation
Regular Expression
<!DOCTYPE html>
<html>
<body>
<h1>Regular Expressions</h1>

<p>Search a string for “vitbhopal", and display the position of


the match:</p>

<p id="demo"></p>

<script>
let text = "Visit vitbhopal!";
let n = [Link](/ vitbhopal /i);
[Link]("demo").innerHTML = n;
</script>
Output:
</body>
</html>
Regular Expression
• Using String Methods:
Regular expressions are often used with the string methods:

Method Description
match(regex) Returns an Array of results
replace(regex) Returns a new String
search(regex) Returns the index of the first match
Output:
JavaScript Form Validation
• HTML form validation can be done by JavaScript.
• If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the
form from being submitted:
• JavaScript Example:

• The function can be called when the form is submitted:


Output:

You might also like