Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Chapter 2

Array, function and string

2.1 Array- declaring an array, initializing an array, defining an array element, looping an array, adding
an array element, sorting an array ,combining an array element, objects as associative arrays.

Array:
It is a collection of more than one element value of similar data type. Array is used store multiple values
required for processing data. An array has user defined name long with index value to identify each element
stores in an array. A combination of array name and an index value is same as having a single variable.

Syntax to declare an array variable:


var array_name=new Array( );
- var is a keyword used to declare a variable
- array_name can be any combination of characters that gives identity to an array.
- new is a keyword that allocates memory to array elements.
- Array ( ) is used to create an array variable. Values to be stored inside array can be mentioned inside
the round brackets.
Example: var products=new Array( );

Syntax to initialize an array:


var array_name=new Array(‘value1’,’value2’, … , ‘value n’);
Example: var products=new Array(‘book’,’pen’,’pencil’,’eraser’);
In the above example, an array named ‘products’ store four values at four different index positions starting
with 0th position.

Individual element can be stored using index position along with array name as shown below:
products[0]=’book’;

length property of an array:


It is used to determine number of elements stored in an array. It determines actual number of elements present
in an array not the size of an array.
Syntax: var variable_name=arrayname.length;
Example: var len=products.length;

Looping an array:
An array element can be accessed using an index variable. By using loop, we can traverse through all the
elements of an array by incrementing index variable by one, after every visit to an element.
In looping, a index variable/counter variable is initially assigned with 0 position. By using for loop or while
loop, each element from an array can be visited with index variable. Initially index variable will point to first
element stored at 0th position. Then index variable is incremented by one to point to next position and so on.
The loop will execute till all elements are visited and index variable points to length value.

Example: Using for to display elements from an array named as products.


for(i=0;i<products.length;i++)
document.write(products[i] + “<br>”);
Example: Output:
<html>
<head></head>
<body> Create an array and display
<h3>Create an array and display elements</h3> elements
<script type="text/javascript"> book
var products=new Array('book','pen','pencil','eraser'); pen
var i; pencil
for(i=0;i<products.length;i++) eraser
{
document.write(products[i] + "<br>"); Total number of elements in an array= 4
}
document.write("<br> Total number of elements in an array= "
+ products.length);
</script>
</body>
</html>

Adding an element in an array:


An element can be added in an array at the time of array declaration or after the declaration with the help of
index position.

1. An array element can be added at the time of array declaration with following syntax:
var array_name=new Array(‘value1’,’value2’, … ,’value n’);
example: var products=new Array(‘book’,’pen’,’pencil’,’eraser’);

2. An array element can be added after the declaration of an array by using index variable to indicate position
inside array. An index variable is initially 0. First element is stored at 0th position and last element is stored at
size-1 position
To access any particular position following syntax is used:
array_name[index position]=’value’;
Example: var products=new Array( );
products[0]=’book’;
products[1]=’pen’;
products[2]=’pencil’;
products[3]=’eraser’;

3. push( ) method: It is used to add a new element at the end of an array. It allocates memory to new element
in an array by incrementing index position by one.

Syntax: array_name.push(“value”);
Example: products.push(“notebook”);
Program: Output:
<html>
<head></head>
<body>
<h3>Adding element to an array</h3>
<script type="text/javascript">
var products=new Array("book","pen","pencil", "eraser");
var i;
for(i=0;i<products.length;i++)
{
document.write(products[i]+"<br>");
}
document.write("<h4>push method</h4>");
products.push("Notebbok");
document.write("After push() method execution Array
elements are:");
for(i=0;i<products.length;i++)
{
document.write("<br>" + products[i]);
}
</script>
</body>
</html>

Sorting An array:
Arranging all array elements in alphabetical order for strings and ascending order for numbers.
sort( ) function is used to perform sorting on array elements.
Syntax: array_name.sort( );
Example: products.sort( );

Program: Output:
<html> Sort an array and display elements
<head></head>
pen
<body> scale
<h3>Sort an array and display elements</h3> pencil
<script type="text/javascript">
eraser
var products=new book
Array("pen","scale","pencil","eraser","book");
var i; Sorted array :
for(i=0;i<products.length;i++) book
{
eraser
document.write(products[i] + "<br>"); pen
}
pencil
products.sort(); scale
document.write("<br>Sorted array : <br>");
for(i=0;i<products.length;i++)
{
document.write(products[i] + "<br>");
}
</script>
</body>
</html>

Combining array elements into a string:


1. concat( ) : It is used to merge all elements of an array into one string.
Syntax: var variable_name=arrayname.concat( );
Above syntax combines elements into one string and separate each element with a comma.
Example: var str1=products.concat( );

Program: Output:
<html> Array elements
<head></head> book
<body> pen
<h3>Array elements</h3> pencil
<script type="text/javascript"> eraser
var products=new Array ("book","pen","pencil", "eraser");
var i;
for(i=0;i<products.length;i++)
{
document.write(products[i] + "<br>");
}
document.write("<br> Combining array elements with
concat() :<br>");
var str=products.concat(); Combining array elements with concat():
document.write(str); book,pen,pencil,eraser
</script>
</body>
</html>

2. join( ) : It is used to merge all elements of an array into one string.


Syntax: var variable_name=arrayname.join(‘char’);
A join method uses comma to separate array elements in a string but we can replace comma with any other
character also. ‘char’ in the syntax indicates character to be replaced with comma.
Example: var str1=products.join(‘*’);

Program: Output:
<html> Array elements
<head></head> book
<body> pen
<h3>Array elements</h3> pencil
<script type="text/javascript"> eraser
var products=new Array("book","pen","pencil", "eraser");
var i; Combining array elements with join():
for(i=0;i<products.length;i++) book*pen*pencil*eraser
{
document.write(products[i] + "<br>");
}
document.write("<br> Combining array elements with
join() :<br>");
var str=products.join('*');
document.write(str);
</script>
</body>
</html>

Changing elements in an array:


1. Reversing array elements:
reverse( ) : It is used to reverse the order of elements of an array.
Syntax: array_name.reverse( ) ;
Example: products.reverse( ) ;

Program: Output:
<html>
<head></head>
<body>
<h3>Reverse elements of an array</h3>
<script type="text/javascript">
var products=new Array("book", "pen", "pencil", "eraser");
var i;
for(i=0;i<products.length;i++)
{
document.write(products[i]+ "<br>");
}
document.write("<hr>");
document.write("<h4>Reverse method</h4>");
products.reverse();
document.write("Array elements are:");
for(i=0;i<products.length;i++)
{
document.write("<br>" + products[i]);
}
</script>
</body>
</html>

2. Removing an element from an array:

shift( ) : It is used to remove first element from an array and return it. It also moves second element at the top
of an array.
Syntax: var variable_name=array_name.shift( );
Example: var str=products.shift( );

Program: Output:
<html>
<head></head>
<body>
<h3>Removing first element from an array</h3>
<script type="text/javascript">
var products=new Array("book", "pen", "pencil", "eraser");
var i;
for(i=0;i<products.length;i++)
{
document.write(products[i]+ "<br>");
}
document.write("<hr>");
document.write("<h4>shift method</h4>");
var str=products.shift();
document.write("Shifted element is : " +str);
document.write("<br> Array elements are:");
for(i=0;i<products.length;i++)
{
document.write("<br>" + products[i]);
}
</script>
</body>
</html>

pop( ) : It is used to return and remove the last element of an array.


Syntax: var variable_name=array_name.pop( ) ;
Example: var str=products.pop( );

Program: Output:
<html>
<head></head>
<body>
<h3>Removing last element from an array</h3>
<script type="text/javascript">
var products=new Array("book","pen","pencil","eraser")
var i
for(i=0;i<products.length;i++)
{
document.write(products[i]+"<br>");
}
document.write("<hr>");
document.write("<h4>pop method</h4>");
var str=products.pop();
document.write("<br> poped element is : " +str);
document.write("<br> Array elements are:");
for(i=0;i<products.length;i++)
{
document.write("<br>" + products[i]);
}
</script>
</body>
</html>
2.2 Function
Defining a function, writing a function, adding arguments, scope of variable and arguments

Function: It is a collection of one or more statements written to execute a specific task.

Defining a function: A function must be defined before it can be called in a JavaScript. A function
in a JavaScript is defined at the beginning of a JavaScript i.e. inside <head> tag or inside <body> tag. If a
function is defined inside <head> tag then all JavaScript code on the web page will know the definition of
that function. Web browser always loads everything from <head> tag before it starts execution of any part
from JavaScript.
Syntax to define a function:
function function_name([Arguments])
{
Statement block;
[return statement;]
}
- Function name is a user defined name. Function name must contain letters, digits or underscore
character. Only one function with same name must exist on a web page. A name cannot begin with a
digit, cannot be a keyword or reserved word. A name should represent action to be performed by the
function.
- Parenthesis are used to pass value if any, to the function. Values are referred as arguments. If the
function does not accept any value then bracket is empty.
- Statement block contains set of statements to be executed when a function is called. All statements of
function are written within a pair of curly brackets.
- Return is optional. It is a keyword that tells the browser to return a value from the function definition
to the statement that called the function. All functions don’t return value, so it is an optional
statement.

Example:
function display ( )
{
alert (“WELCOME TO JAVASCRIPT”);
}
When the above function is executed(called), it displays alert dialog box with the message
as ’WELCOME TO JAVASCRIPT’

Adding an argument:
A function need data to perform its task. Data required for processing task is either declared and accepted
inside function definition or it can be accepted in the form argument pass in function call.
Argument can be one or more variables(values) that are declared inside round brackets followed by function
name in function definition.

Syntax: function function_name (Argument 1, Argument 2, . . ., Argument n)


{
body of function;
}

Example: function add (no1, no2) // No need to specify data type of any argument
{
var no3;
no3=no1+no2;
document. write (“addition = “+ no3);
}
In the above example, function add accepts two arguments as no1 and no2. These two arguments are used
inside function to process addition.

Program: Output:
<html>
<head>
<script type="text/javascript">
function add(no1,no2)
{
var no3;
no3=no1+no2;
document. write ("Addition = " + no3);
}
</script>
</head>
<body>
<script type="text/javascript">
add (10,20);
</script>
</body>
</html>

Scope of variable and arguments:


Scope of variable and argument describe whether a statement of JavaScript can use (access)
variable/argument. A variable is considered in scope if the statement can access the variable. A variable out
of scope if a statement cannot access the variable.
A variable can be declared inside a function and it is known as local variable for that function. This variable
is not accessible by other functions in the script as they are not aware of this local variable.
A variable can be declared outside the function and it is known as global variable. This variable can be
access by any statement, function in a script.

Program: Output:
<html>
<head>
<script type="text/javascript">
var a=10;
function display( )
{
document.write("Inside Function display<br>");
document.write("Global variable a= " + a);
var b=20;
document.write("<br>Local variable b= " +b);
}

function show()
{
document.write("<br>Inside Function show <br>");
document.write("Global variable a= " + a);
var c=30;
document.write("<br>Local variable c= " + c);
}
</script>
</head>
<body>
<h3>Scope of variable</h3>
<script type="text/javascript">
display( );
document.write("<hr>")
show( );
</script>
</body>
</html>

2.3 Calling a function


Calling a function with or without an argument, calling function from HTML, function calling
another function, Returning a value from a function.

Calling a function: A function can be called with function name followed by brackets and arguments
(values) if any.
Syntax : function_name([Argument 1,Argument 2, . . . ,Argument n]);
Example: display( );

Note: A function definition can be placed inside <head> tag or <body> tag.
1. Calling a function without an argument: A function definition is placed within the <head> tag and the
function call is placed within the <body> tag. When a function is called, empty bracket followed by function
name is a function call that does not contain any argument. When function is called, browser passes control
to the function definition and executes statements from the code block.
Example:

Function definition:
function display( )
{
alert(“Welcome to JavaScript”);
}

Function call:
display( );

In the above example,when function call display( ) will execute, browser will pass the control to function
definition. Execution of function will display alert dialog box with the message “Welcome to javascript”.

Program: Output:
<html>
<head>
<script type="text/javascript">
function welcome()
{
alert("Welcome to javascript");
}
</script>
</head>
<body>
<script type="text/javascript">
welcome();
</script>
</body>
</html>
2. Calling a function with argument: Calling a function with arguments requires a function call with
argument values. When a function is called, its function call contains function name followed by argument
values inside round brackets. Argument values inside the bracket tells the browser to assign these values to
the corresponding arguments in the function.

Syntax: function_name(value1,value2,…,value n);


Example:
Function definition:
function add(no1,no2 )
{
alert(“Addition = “ + no1+no2);
}

Function call:
add(2,3);

In the above example,when function call add (2,3) will execute, browser will pass values 2 and 3 as function
arguments to function definition. Execution of function will display alert dialog box with the addition of no1
and no2.

Program: Output:
<html>
<head>
<script type="text/javascript">
function add(no1,no2)
{
document.write("<br> number 1 = " + no1);
document.write("<br> number 2 = " + no2);
document.write("<br> Addition = " + (parseInt(no1) +
parseInt(no2)));
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("Program on function with argument");
add(2,3);
</script>
</body>
</html>

Calling a function from HTML:


A function can be called from HTML code on a web page. A function will be called in response to an event,
such as we page loading on browser,clicking on button,etc. In HTML code, function call is assigned as a
value of HTML tag attribute.
Syntax: <tag_name event_name=”function_name( )”>
Example: <body onload=”welcome( )”>

Program: Output:
<html> //onload event calls welcome function at the time of
<head> loading browser contents(web page)
<script type="text/javascript">
function welcome()
{
alert("Welcome to JavaScript");
}

function goodbye()
{
alert("Thank you for visiting");
}
</script> //onclick event of submit button calls goodbye
</head> function when user click on submit button.
<body onload="welcome()">
<form>
<input type="submit" onclick="goodbye()">
</form>
</body>
</html>

Function calling another function:


A function can be called inside body of another function by writing function call statement inside body of a
function.
Syntax: function calling_function_name()
{
[Statements;]
Function call to other function();
[Statements;]
}
In the above example, calling function definition (body of function) contains function call to other function.

Example: function display()


{
add(2,3); // function call to add function inside body of display function
}
Program: Output:
<html> After clicking on submit button first welcome
<head> function is executed which in turn calls chapter1
<script type="text/javascript"> function.
function welcome() Output for welcome( ):
{
alert("Welcome to JavaScript");
chapter1();
}
function chapter1()
{
alert("Welcome to Chapter1");
} Output for chapter1( ):
</script>
</head>
<body>
<form>
<input type="submit" onclick="welcome()">
<form>
</body>
</html>
Returning a value from a function:
A function can execute and return a value to the calling statement after completing its execution. To return a
value from function,return keyword is used followed by return value.
Syntax: function function_name( )
{
Statements;
return value;
}
When a called function returns a value, it is stored inside a variable or displayed on a web page by calling
function.
Syntax for calling a function with return value: variable_name=function_name( );

Example:
function add(no1,no2)
{
var no3;
no3=parseInt(no1)+parseInt(no2);
return no3;
}
In calling function, add function is called with : var result=add(2,3);

Program: Output:
<html>
<head>
<script type="text/javascript">
function add(no1,no2)
{
var no3;
no3=parseInt(no1)+parseInt(no2);
return no3;
}
</script>
</head>
<body>
<script type="text/javascript">
var result;
result=add(2,3);
document.write("Addition = " + result);
</script>
</body>
</html>
Creating pop-up window:
A pop-up window is a small user interface element that will be displayed on a web page when an event
triggers. A pop-up window can be used to open another link on a web page in same window or in a new tab.
For creating a pop-up window, window object along with open method is used with arguments.
Syntax: window.open(URL,name,features,replace);

URL=” address of web page” : It specify URL of a web page to be opened in a pop-up window. If
URL is not specified, then a new window with about:blank will open on a web page.

Name=”_blank/_parent/_self/_top/name” : It specify the target attribute or the name of the


window in which link has to be opened. It can have following values:
_blank: URL is loaded into a new window. It is a default value.
_parent: URL is loaded into the parent frame.
_self: URL replaces the current page.
_top: URL replaces any framesets that may be loaded.
Name: it specify name of the window.

Features=”height/width/top/left/menubar/toolbar/status/resizable/scrollbars”: It specify
list of features that specify parameters to be set for pop-up window. All parameters are separated with a
comma. The list of parameters:
- height=pixels: Specify height of pop-up window
- width=pixels: Specify width of pop-up window
- top=pixels: Specify position of pop-up window from top
- left=pixels: Specify position of pop-up window from left
- menubar=”yes/no” : Shows or hides the browser menu
- toolbar=”yes/no”: Shows or hides the navigation bar
- status=”yes/no”: Shows or hides the status bar
- resizable=”yes/no”: Whether or not the window is resizable
- scrollbars=”yes/no”: Whether or not to display scroll bars

Replace=”true/false” : Specifies whether the URL creates a new entry or replace the current entry in the
browser history. Works only if the URL is loaded into the same window.
- true: URL replaces the current document in the history list
- false: URL created a new entry in the browser history list

Example:
<html>
<head>
</head>
<body>
<input type="button" value="open popup" onclick="window.open( 'example/page1.html', '_blank ',
'height=400 , width=400, top=200, left=200, resizable=yes')">
</body>
</html>

Output:
Chapter 2.4 Strings
Manipulate a string, joining a string, retrieving a character from given position,
retrieving a position of character in a string ,dividing text, copying a sub string,
converting string to number and numbers to string, changing the case of string, finding
a Unicode of a character-charCodeAt(),fromCharCode().

String: It is a collection of characters. String is used for storing and manipulating text. A string can be
declared in a single quote or double quote.
Example: var a=’hello’; OR var a=”hello”;

String manipulation is the process of working with string. It includes performing various operations
on string such as join, search, copy, split, etc.

Joining a string:
Concatenating / merging two strings : in joining operation a new string is formed from two strings, by
placing contents of second string at the end of first string. New string contains all characters from both the
strings. ‘+’ operator is used to join / concatenate two strings.

Syntax: string1 + string2;


Example: var str1=” hello”;
var str2=”Welcome to CSS”;
var str3=str1+str2;
In the above example, variable str3 stores string as ‘hello Welcome to CSS’.

Program: Output:
<html>
<head></head>
<body>
<script type="text/javascript">
var str1="hello";
var str2=" Welcome to CSS";
var str3=str1+str2;
document.write("String1 = " + str1);
document.write("<br> String2 = " + str2);
document.write("<br>Concatenated string = " + str3);
</script>
</body>
</html>

Retrieving a character from given position:


A character can be retrieved from a given position by using the charAt( ) method of string object.
Syntax: variable_name=stringobj.charAt( index);
charAt( ) function accepts one argument as index that specify position from which a character has to be
retrieved from string object.
Example: var str1=”Welcome to CSS”;
var ch=str1.charAt(5);
in the above example, variable ch will store character as ‘m’ which is at 3rd index position as array stores
characters from 0th index position.
Program: Output:
<html>
<head></head>
<body>
<script type="text/javascript">
var str1="Welcome to CSS";
var ch=str1.charAt(5);
document.write("Character at 5th index position = " + ch);
</script>
</body>
</html>

Retrieving a position of character in a string:

To retrieve a position of character from a string, indexOf( ) method of string object is used. indexOf( )
method returns the index position of a character passed as an argument in charAt( ) method. If the character
is not in the string then the method returns -1 value.
Syntax: var index=stringobject.indexof(‘char’);

Example: var str1=”Welcome”;


var index=str1.indexOf(‘m’);
In the above example, indexOf( ) method returns 5 as a position of character ‘m’ inside string ‘Welcome’.

Program: Output:
<html> If specified character is in the list:
<head></head>
<body>
<script type="text/javascript">
var str1;
var str2;
str1=prompt("Enter string"," ");
str2=prompt("Enter character"," ");
var index=str1.indexOf(str2);
if(index != -1) If specified character is not in the list:
{
document.write("Character "+str2+ " is at index
position= "+index);
}
else
{
document.write("Character is not in the list");
}
</script>
</body>
</html>
Dividing text:
A comma separated/delimited string contains multiple data elements separated with comma. Comma is used
to specify the beginning and end of each data element. split( ) method of string object is used to separate
each data element into its own string. split( ) method creates a new array and then copies portions of the
string,called a sub string into its array elements.

Syntax: var newarray=stringvariable.split(‘delimiter string’);


- delimiter string as an argument to the method specify separator used to separate data elements in a string.

Example: var newarray=str1.split(‘,’);


In the above example, split ( ) method divides string stored in str1 with respect to a separator ‘comma’ and
stores separated elements in an array variable ‘newarray’.

Program: Output:
<html> datastring=
<head></head> JavaScript,VBScript,Python,Android
<body>
<script type="text/javascript">
var datastring="JavaScript,VBScript,Python,Android"; String after split in array elements
var newarray=datastring.split(','); JavaScript
document.write("datastring= " + datastring); VBScript
document.write("<hr><br>String after split in array elements"); Python
for(var i=0;i<newarray.length;i++) Android
{
document.write("<br>" + newarray[i]);
}
</script>
</body>
</html>

Copying a sub string:


substring( ) and substr( ) are the two methods used to copy sub string.

1. substring( ) : This method copies a substring from a string based on a beginning and an end position,
passed as an argument to the substring( ).
Syntax: stringvar=string.substring(start,end);
- start : specify position of first character to be copied from string.
- end : specify position of character whose previous character will be last character to be copied from string.

Example: var newstr=string1.substring(4,12);


In above example, substring ( ) method will copy characters from start position i.e. 4th position upto 11th
position in variale newstr.

Data string : “Welcome to JavaScript” //


Newstring : ome to J

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
W e l c o m e t o J a v a S c r i p t

Program: Output:
<html> datastring= Welcome to JavaScript
<head></head>
<body> new substring= ome to J
<script type="text/javascript">
var datastring="Welcome to JavaScript";
var newstr=datastring.substring(4,12);
document.write("datastring= " + datastring);
document.write("<hr>new substring= " +newstr);
</script>
</body>
</html>

2. substr( ) : This method is used to copy sub string from a string based on starting position and number of
characters pass as an argument to the method.
Syntax: stringvar=string.substr(startposition,noofchar);
- start position specify position of first character from string
- noofchar specify number of characters to be copied from first character from the string.

Example: var newstring=datastring.substr(4,10);


In the above example, substr( ) method copies 10 characters from the 4th position from a datastring object.

Data string : “Welcome to JavaScript” //


Newstring : ome to Jav

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
W e l c o m e t o J a v a S c r i p t

Program: Output:
<html>
<head></head> datastring= Welcome to JavaScript
<body>
<script type="text/javascript"> new substring= ome to Jav
var datastring="Welcome to JavaScript";
var newstr=datastring.substr(4,10);
document.write("datastring= " + datastring);
document.write("<hr>new substring= " +newstr);
</script>
</body>
</html>

Converting number to string:


A number is a value that can be used in a calculation. A string is a text and can include numbers but these
numbers can not be used in calculations. To convert a number i.e. numeric value into string, toString( )
method of number object is used. It converts a number in integer form as well as decimal form (float) to
string.
Syntax: variable=number.toString( );
Example: var number1=100;
var str1=number1.toString( );
Concatenate operator (+) is used to combine a string and a number. This operator automatically calls
toString ( ) method to convert number into a string.

<html>
<body>
<script type="text/javascript">
var data1=10;
var data2=20;
var str1=data1.toString();
var str2=data2.toString();
document.write(str1+str2);
//document.write(data1+data2);
</script>
</body>
</html>

Converting string to number:


1. parseInt( ) : This method converts a number stored in a string into a numeric value which is a whole
number.
Syntax: var number=parseInt(string_name);
Example: var no=parseInt(str1);

<html> a= 4
b= 5
<head></head> Addition without conversion= 45
<body> Addition with conversion= 9
<script type="text/javascript">
var a=prompt("Enter first number","");
var b=prompt("Enter second number","");
document.write("a= "+a);
document.write("<br>b= "+b);
var c=a+b;
document.write("<br> Addition without conversion= " +c);
var d=parseInt(a);
var e=parseInt(b);
var f=d+e;
document.write("<br> Addition with conversion=" +f);
</script>
</body>
</html>

2. parseFloat( ) : This method converts a floating number stored in string into a float / decimal value.
Syntax: var number=parseFloat(string_name);
Example: var no=parseFloat(str1);

<html> a= 2.47
<head></head> b= 3.50
<body> Addition without conversion= 2.473.50
<script type="text/javascript"> Addition with conversion=
var a=prompt("Enter first number",""); 5.970000000000001
var b=prompt("Enter second number","");
document.write("a= "+a);
document.write("<br>b= "+b);
var c=a+b;
document.write("<br> Addition without conversion= " +c);
var d=parseFloat(a)+parseFloat(b);
document.write("<br> Addition with conversion= " +d);
</script>
</body>
</html>
Changing case of string:
In some application, for string validation and comparison , JavaScript developers need to convert string into
either lowercase or uppercase. For changing case of string two methods of string object are used such as
toLowerCase( ) and toUpperCase( ).

1. toLowerCase( ) : This method is used to convert a given string characters into lowercase letters. After
conversion it returns converted string.
Syntax: str=stringobj.toLowerCase( );
Example: var str=”WELCOME to CSS”;
document.write(“ Lowercase characters= “ +str.toLowerCase( ));

<html>
<head></head>
<body>
<script type="text/javascript">
var str1="WELCOME to CSS";
document.write("Original String : = " + str1);
document.write("<br>Converted into Lowercase : = " +
str1.toLowerCase( ));
</script>
</body>
</html>

2. toUpperCase( ) : This method is used to convert a given string characters into uppercase letters. After
conversion it returns converted string.
Syntax: str=stringobj.toUpperCase( );
Example: var str=”welcome TO CSS”;
document.write(“Uppercase characters= “ +str.toUpperCase( ));

<html>
<head></head>
<body>
<script type="text/javascript">
var str1="welcome TO css";
document.write("Original String : = " + str1);
document.write("<br>Converted into Uppercase : = " +
str1.toUpperCase( ));
</script>
</body>
</html>

Finding a unicode of a character (ASCII):


Unicode is a standard that assigns a number to every character,number and symbol that can be displayed on
a computer screen. Unicode is a number that computer can understand when any character,number or
symbol is entered in it.

1. charCodeAt( ) : This method is used to return a unicode of specified character.


Syntax: var code=letter.charCodeAt( );
Example: var ch=’a’;
document.write(ch.charCodeAt( ));
Output: 97
<html>
<head></head>
<body>
<script type="text/javascript">
var ch='a';
document.write("Unicode of " + ch + "is = " +
ch.charCodeAt());
</script>
</body>
</html>

2. fromCharCode( ) : This method is used to return a character for specified code.


Syntax: var character=String.fromCharCode(code);
Example: var character=String.fromCharCode(97);
Document.write(ch);
Output: a
<html>
<head></head>
<body>
<script type="text/javascript">
var code=97;
document.write("Character at unicode " + code + " is =
" + String.fromCharCode(code));
</script>
</body>
</html>

You might also like