Unit-2 Array, Function and String
Unit-2 Array, Function and String
ARRAY,FUNCTION
AND STRING
JAVASCRIPT ARRAY
JavaScript array is an object that represents a
collection of similar type of elements.
There are 3 ways to construct array in JavaScript
By array literal
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
3) JAVASCRIPT ARRAY CONSTRUCTOR (NEW
KEYWORD)
Here, you need to create instance of array by
passing arguments in constructor so that we don't
have to provide value explicitly.
The example of creating object by array constructor
is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
INITIALIZING AN ARRAY
Initialization is the process of assigning values to an
array. While initializing an array ,all the elements
should be placed in parenthesis and separated by
commas.
document.write("<br>"+a[i]+"<br>")
}
</script>
</body>
</head>
<html>
SORTING AN ARRAY ELEMENTS
Index of array specifies the order in which elements appear in an array
when for loop is used to display array sometimes we want elements to
appear in sorted order.
sort() method sorts the elements of an array in ascending order.
Syntax:
arrayObj.sort();
<html>
<head>
<title>JavaScript Array sort Method</title> </head>
<body>
<script type = "text/javascript">
var arr = new Array("orange", "mango", "banana", "sugar");
var sorted = arr.sort();
document.write("Returned string is : " + sorted );
</script>
</body>
</html>
Array reverse() method:
sort method sort all elements in ascending order,
we can use reverse method to display sorted element in
descending order.
Syntax: array.reverse();
NUMERIC SORT
array.shift();
pop() method : this method is used to remove
last element and returns the removed element
from an array.
Syntax:
array.pop();
OBJECT AS ASSOCIATIVE ARRAY
Associative array are dynamic objects that the user
redefines as needed .
When user assigns values to keys in a variable of type
Array, it transforms into an object and loses the
attributes and methods of previous data type.
We can create it by assigning a literal to a variable.
Syntax:
var a={“one”:1,”two”:2,”three”:3};
//program to demonstrate associative array
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var array = { "alpha": 1, "beta": 2, "gama": 3 };
var x = array["beta"];
document.write(x);
</script>
</body>
</html>
JAVASCRIPT FUNCTIONS
A JavaScript function is a block of code designed to
perform a particular task.
A JavaScript function is executed when "something"
invokes it (calls it).
There are mainly two advantages of JavaScript
functions.
Code reusability: We can call a function several times so
it save 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.
A JavaScript function can be defined
using function keyword.
//defining a function
<script type = "text/javascript">
<!-- function functionname (parameter-list)
{
statements
}
//-->
</script>
//calling a function
Syntax:
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
o/p:javascript concat example
RETRIEVING A CHARACTER FROM GIVEN POSITION
JavaScript String charAt(index)
Method:each character in a string is an array
element that can be identified by its index.
The JavaScript String charAt() method returns
the character at the given index.
Syntax: string.charAt(index);
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
o/p:v
RETRIEVING A POSITION OF CHARACTER IN A STRING
JavaScript String indexOf(str) Method:The JavaScript String
indexOf(str) method returns the index position of the given string.
Syntax: string.indexOf(‘character’);
<script>
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
o/p:11
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>
o/p: 16
DIVIDING STRING
JavaScript String split() Method:
Splits a String object into an array of strings by
separating the string into substrings.
string.split([separator], [limit]);
separator − Specifies the character to use for
separating the string. If separator is omitted, the
array returned contains one element consisting of the
entire string.
limit − Integer specifying a limit on the number of
splits to be found
EXAMPLE:
<html>
<head>
<script>
var str = 'Welcome to the javaTpoint.com'
var arr = str.split(" ", 3);
document.write(arr);
</script>
</head>
<body>
</body>
</html>
o/p: Welcome,to,the
COPYING A SUBSTRING
JavaScript String substring() Method
The JavaScript string substring() method fetch the
string on the basis of provided index and returns the
new sub string.
It works similar to the slice() method with a
difference that it doesn't accepts negative indexes.
This method doesn't make any change in the original
string.
Syntax:
string.substring(start,end)
Parameter:
start - It represents the position of the string from
where the fetching starts.
end - It is optional. It represents the position up to
which the string fetches.
EXAMPLE:
<script>
var str="Javatpoint";
document.writeln(str.substring(0,4));
</script>
Output:Java
STRING SUBSTR() METHOD
The JavaScript string substr() method fetch the part
of the given string and return the new string. The
number of characters to be fetched depends upon the
length provided with the method. This method doesn't
make any change in the original string.
Syntax:
string.substr(start,length)
Parameter:
Output:
Java
slice() method is used to fetch the part of the string and returns
the new string.
It required to specify the index number as the start and end
parameters to fetch the part of the string. The index starts from
0.
Syntax: string.slice(start,end)
Parameter:
start - It represents the position of the string from where the
fetching starts.
end - It is optional. It represents the position up to which the
string fetches. In other words, the end parameter is not included.
<script>
var str = "Javatpoint";
document.writeln(str.slice(2,5));
</script>
o/p:
vat
CHANGING THE CASE OF STRING
JavaScript String toLowerCase() Method
The JavaScript String toLowerCase() method returns
the given string in lowercase letters.
Syntax: string. toLowerCase() ;
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
o/p:javascript tolowercase example
JavaScript String toUpperCase() Method
The JavaScript String toUpperCase() method
returns the given string in uppercase letters.
Syntax: string.toUppercase();
<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
Number.parseInt(string)
Parameter
number.toString( [radix] )
Parameter Details:
string.charCodeAt(index)
Parameter:
index - It represent the position of a character.
EXAMPLE:
<script>
var x="Javatpoint";
document.writeln(x.charCodeAt(3));
</script>
o/p:97
FROMCHARCODE()
JavaScript fromCharCode() method is used to
convert the Unicode values into characters.
It is a static method of the String object so the syntax
will remain always same.
Syntax: String.fromCharCode(n1, n2, ..., nX)
Output: // HELLO
QUESTIONS:
1. Differentiate between concat() and join()
methods of array object.
2. Write the use of chatAt() and indexof() with
syntax and example.
3. Write a JavaScript that will replace following
specified value with another value in string.
String = “I will fail” Replace “fail” by “pass”.