Mod - 2 (1) - Read-Only
Mod - 2 (1) - Read-Only
Types are known at compile time Compile time type checking is impossible
Collection of data members and methods is The number of data members and methods of
fixed at compile time an object can change during execution
USES OF JAVASCRIPT
• The JavaScript was initially introduced to provide
programming capability at both the server and client ends of
web connection
JavaScript therefore is implemented at 2 ends:
1. Client end
2. Server end
• The client side JavaScript is embedded in XHTML
documents and is interpreted by the browser
• It also provides some means of computation, which serves
as an alternative for some tasks done at the server side
• Interactions with users through form elements, such as
buttons and menus, can be conveniently described in
JavaScript. Because button clicks and mouse movements
are easily detected with JavaScript, they can be used to
trigger computations and provide feedback to the user.
• For example, when a user moves the mouse cursor from a
text box, JavaScript can detect that movement and check the
appropriateness of the text box’s value (which presumably
was just filled by the user).
• Even without forms, user interactions are both possible and
simple to program in JavaScript.
• These interactions, which take place in dialog windows,
include getting input from the user and allowing the user to
make choices through buttons.
• It is also easy to generate new content in the browser
display dynamically.
• This transfer of task ensures that the server is not
overloaded and performs only required task
• But client side JavaScript cannot replace serves side
JavaScript; because server side software supports file
operations, database access, security, networking etc
• JavaScript is also used as an alternative to java applets.
• Programming in JavaScript is much simpler than
compared to java
• JavaScript support DOM [Document Object Model]
which enables JavaScript to access and modify CSS
properties and content of any element of a displayed
XHTML document
Document Object Model
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print
name"/>
</form>
• javascript - document.getElementById() method
• getElementById() method
• Example of getElementById()
• The document.getElementById() method returns
the element of specified id.
• In the previous page, we have
used document.form1.name.value to get the
value of the input value. Instead of this, we can
use document.getElementById() method to get
value of the input text. But we need to define id
for the input field.
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="numbe
r"/><br/>
<input type="button" value="cube" onclick="getcube()"/
>
</form>
• Javascript - document.getElementsByName()
method
• getElementsByName() method
• Example of getElementsByName()
• The document.getElementsByName() method
returns all the element of specified name.
• The syntax of the getElementsByName() method
is given below:
• document.getElementsByName("name")
• Here, name is required.
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders"
>
</form>
• Javascript - document.getElementsByTagName()
method
• getElementsByTagName() method
• Example of getElementsByTagName()
• The document.getElementsByTagName() metho
d returns all the element of specified tag name.
• The syntax of the getElementsByTagName()
method is given below:
• document.getElementsByTagName("name")
• Here, name is required.
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraph
s by getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button
>
• Javascript - innerHTML
• javascript innerHTML
• Example of innerHTML property
• The innerHTML property can be used to
write the dynamic html on the html document.
• It is used mostly in the web pages to generate
the dynamic html such as registration form,
comment form, links etc.
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br>
<textarea rows='5' cols='80'></textarea>
<br><input type='submit' value='Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment“onclick="showcommentform()
">
<div id="mylocation"></div>
</form>
• Javascript - innerText
• javascript innerText
• Example of innerText property
• The innerText property can be used to write the
dynamic text on the html document. Here, text
will not be interpreted as html text but a normal
text.
• It is used mostly in the web pages to generate the
dynamic content such as writing the validation
message, password strength etc.
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
• JavaScript Objects
• A javaScript object is an entity having state and
behavior (properties and method). For example:
car, pen, bike, chair, glass, keyboard, monitor etc.
• JavaScript is an object-based language.
Everything is an object in JavaScript.
• JavaScript is template based not class based.
Here, we don't create class to get the object. But,
we direct create objects.
• Creating Objects in JavaScript
• There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using
new keyword)
3. By using an object constructor (using new
keyword)
1) JavaScript Object by object literal
• The syntax of creating object using object literal is given
below:
• object={property1:value1,property2:value2.....propertyN:va
lueN}
• As you can see, property and value is separated by : (colon).
• Let’s see the simple example of creating object in
JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
2) By creating instance of Object
• The syntax of creating object directly is given
below:
• var objectname=new Object();
• Here, new keyword is used to create object.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp
.salary);
</script>
3) By using an Object constructor
• Here, you need to create function with
arguments. Each argument value can be
assigned in the current object by using this
keyword.
• The this keyword refers to the current object.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
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>
S.N
o
JavaScript Object
Methods Description Methods
• The JavaScript date object can be used to get year, month and day.
You can display a timer on the webpage by the help of JavaScript
date object.
• You can use different Date constructors to create date object. It
provides methods to get and set day, month, year, hour, minute and
seconds.
• Constructor
• You can use 4 variant of Date constructor to create date object.
• Date()
• Date(milliseconds)
• Date(dateString)
• Date(year, month, day, hours, minutes, seconds, milliseconds)
Methods JavaScript
Description Date Methods
getDate() It returns the integer value between 1 and 31 that represents the
day for the specified date on the basis of local time.
getDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of local time.
getFullYears() It returns the integer value that represents the year on the basis of
local time.
getHours() It returns the integer value between 0 and 23 that represents the
hours on the basis of local time.
getMilliseconds() It returns the integer value between 0 and 999 that represents the
milliseconds on the basis of local time.
getMinutes() It returns the integer value between 0 and 59 that represents the
minutes on the basis of local time.
getMonth() It returns the integer value between 0 and 11 that represents the
month on the basis of local time.
JavaScript Date Example
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month
+"/"+year);
</script>
JavaScript Current Time Example
abs
alias
/^a...s$/
abyss
Alias
Create a RegEx
ac
[abc]
Hey Jude
abc de ca
• Here, [abc] will match if the string you are trying to
match contains any of the a, b or c.
• You can also specify a range of characters using - inside
square brackets.
• [a-e] is the same as [abcde].
• [1-4] is the same as [1234].
• [0-39] is the same as [01239].
• You can complement (invert) the character set by using
caret ^ symbol at the start of a square-bracket.
• [^abc] means any character except a or b or c.
• [^0-9] means any non-digit character.
• . - Period
• A period matches any single character (except
newline '\n').
Expression String Matched?
a No match
ac 1 match
.. acd 1 match
2 matches
acde (contains 4
characters)
• ^ - Caret
• The caret symbol ^ is used to check if a
string starts with a certain character.
Expression String Matched?
a 1 match
^a abc 1 match
bac No match
abc 1 match
Expression String
a$ formula
cab
• * - Star
• The star symbol * matches zero or more
occurrences of the pattern left to it
Expression String Matched?
mn 1 match
man 1 match
mann 1 match
ma*n
No match (a is not
main
followed by n)
woman 1 match
• + - Plus
• The plus symbol + matches one or more
occurrences of the pattern left to it
Expression String Matched?
No match (no a
mn
character)
man 1 match
No match (a is not
main
followed by n)
woman 1 match
• ? - Question Mark
• The question mark symbol ? matches zero or
one occurrence of the pattern left to it.
Expression String
mn
man
ma?n maan
main
woman
• {} - Braces
• Consider this code: {n,m}. This means at
least n, and at most m repetitions of the
pattern left to it.
Expression String
abc dat
abc daat
a{2,3}
aabc daaat
aabc daaaat
• Let's try one more example. This RegEx [0-
9]{2, 4} matches at least 2 digits but not more
than 4 digits.
Expression String
ab123csde
1 and 2
• | - Alternation
• Vertical bar | is used for alternation
(or operator).
Here, a|b match any string that contains either a or b
cde No match
1 match (match
ade
a|b at ade)
3 matches (at
acdbea
acdbea)
• () - Group
• Parentheses () is used to group sub-patterns.
For example, (a|b|c)xz match any string that
matches either a or b or c followed by xz
Expression String
ab xz
(a|b|c)xz abxz
axz cabxz
• \ - Backslash
• Backslash \ is used to escape various characters
including all metacharacters.
For example,
• \$a match if a string contains $ followed by a.
Here, $ is not interpreted by a RegEx engine in a
special way.
• If you are unsure if a character has special
meaning or not, you can put \ in front of it. This
makes sure the character is not treated in a
special way.
• Special Sequences
• Special sequences make commonly used
patterns easier to write. Here's a list of special
sequences:
• \A - Matches if the specified characters are at
the start of a string.
Expression String
the sun
\Athe
In the sun
• \b - Matches if the specified characters are at
the beginning or end of a wordExpression
Expression String
football
\bfoo
a football
a football
the foo
foo\b
the afoo test
the afootest
• \B - Opposite of \b. Matches if the specified
characters are not at the beginning or end of a
word.
Expression String
football
\Bfoo
a football
a football
the foo
foo\B
the afoo test
the afootest
• \d - Matches any decimal digit. Equivalent
to [0-9]
Expression String
12abc3
\d
JavaScript
• \D - Matches any non-decimal digit.
Equivalent to [^0-9]
Expression String
1ab34"50
\D
1345
• \s - Matches where a string contains any
whitespace character. Equivalent to [
\t\n\r\f\v].
Expression String
JavaScript
\s RegEx
JavaScriptRegEx
• \S - Matches where a string contains any non-
whitespace character. Equivalent to [^
\t\n\r\f\v].
Expression String
\S a b
• \w - Matches any alphanumeric character
(digits and alphabets). Equivalent to [a-zA-Z0-
9_]. By the way, underscore _ is also
considered an alphanumeric character.
Expression String
12&": ;c
\w
%"> !
• \W - Matches any non-alphanumeric
character. Equivalent to [^a-zA-Z0-9_]
Expression String
1a2%c
\W
JavaScript
• \Z - Matches if the specified characters are at
the end of a string.
Expression String
I like JavaScript
I like JavaScript
JavaScript\Z
Programming
JavaScript is fun
Exception Handling in JavaScript
if(firstpassword==secondpassword){
return true;
}
Else
{
alert("password must be same!");
return false;
}
}
</script>
<form name="f1" action="register.jsp" onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>
JavaScript Number Validation
Let's validate the textfield for numeric value only. Here, we are using isNaN()
function.
<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>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
• JavaScript validation with image
• Let’s see an interactive JavaScript form
validation example that displays correct and
incorrect image if input is correct or incorrect.
<script>
function validate(){
var name=document.f1.name.value;
var password=document.f1.password.value;
var status=false;
if(name.length<1){
document.getElementById("nameloc").innerHTML=
" <img src='unchecked.gif'/> Please enter your name";
status=false;
}else{
document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";
status=true;
}
if(password.length<6){
document.getElementById("passwordloc").innerHTML=
" <img src='unchecked.gif'/> Password must be at least 6 char long";
status=false;
}else{
document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";
}
return status;
}
</script>
<form name="f1" action="#" onsubmit="return validate()">
<table>
<tr><td>Enter Name:</td><td><input type="text" name="name"/>
<span id="nameloc"></span></td></tr>
<tr><td>Enter Password:</td><td><input type="password" name="p
assword"/>
<span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td><
/tr>
</table>
</form
JavaScript email validation
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output of the above example
Arun
Varun
John
3) JavaScript array constructor (new keyword)
It copies the part of the given array with its own elements and returns the modified array.
It creates an iterator object and a loop that iterates over each key/value pair.
entries()
It determines whether all the elements of an array are satisfying the provided function conditions.
every()
It creates a new array carrying sub-array elements concatenated recursively till the specified depth.
flat()
It maps all array elements via mapping function, then flattens the result into a new array.
flatMap()
It fills elements into an array with static values.
fill()
It creates a new array carrying the exact copy of another array element.
from()
It returns the new array containing the elements that pass the provided function conditions.
filter()
It returns the value of the first element in the given array that satisfies the specified condition.
find()
It returns the index value of the first element in the given array that satisfies the specified condition.
findIndex()
It invokes the provided function once for each element of an array.
forEach()
It checks whether the given array contains the specified element.
includes()
It searches the specified element in the given array and returns the index of the first match.
indexOf()
It tests if the passed value ia an array.
isArray()
It creates a new iterator object carrying values for each index in the array.
values()
join() It joins the elements of an array as a string.
keys() It creates an iterator object that contains only the keys of the array, then loops through these keys.
lastIndexOf() It searches the specified element in the given array and returns the index of the last match.
map() It calls the specified function for every array element and returns the new array
of() It creates a new array from a variable number of arguments, holding any type of argument.
reduce(function, initial) It executes a provided function for each value from 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.
slice() It returns a new array containing the copy of the part of the given 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.
JavaScript String
charCodeAt() It provides the Unicode value of a character present at the specified index.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a 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.
substring() It is used to fetch the part of the given string on the basis of the specified index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative
index.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.
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.
1) JavaScript String charAt(index) Method
• The JavaScript String charAt() method returns
the character at the given index
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
v
2) JavaScript String concat(str) Method
• The JavaScript String concat(str) method
concatenates or joins two strings.
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
javascript concat example
3) JavaScript String indexOf(str) Method
• The JavaScript String indexOf(str) method
returns the index position of the given string
<script>
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
11
4) JavaScript String lastIndexOf(str) Method
• The JavaScript String lastIndexOf(str) method
returns the last index position of the given string.
<script>
var s1="javascript from javatpoint indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
16
5) JavaScript String toLowerCase() Method
• The JavaScript String toLowerCase() method
returns the given string in lowercase letters.
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
javascript tolowercase example
6) JavaScript String toUpperCase() Method
• The JavaScript String toUpperCase() method
returns the given string in uppercase letters.
• <script>
• var s1="JavaScript toUpperCase Example";
• var s2=s1.toUpperCase();
• document.write(s2);
• </script>
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.
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
cde
• JavaScript String trim() Method
• The JavaScript String trim() method removes
leading and trailing whitespaces from the
string.
<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
javascript trim
• JavaScript String split() Method
<script>
var str="This is Java";
document.write(str.split(" ")); //splits the given
string.
</script>
• JavaScript Math
• The JavaScript math object provides several
constants and methods to perform
mathematical operation. Unlike date object, it
doesn't have constructors.
• JavaScript Math Methods
• Let's see the list of JavaScript Math methods
with description.
Methods Description
abs() It returns the absolute value of the given number.
ceil() It returns a smallest integer value, greater than or equal to the given number.
floor() It returns largest integer value, lower than or equal to the given number.
toExponential() It returns the string that represents exponential notation of the given number.
toFixed() It returns the string that represents a number with exact digits after a decimal point.
Property Description
Method Description