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

CSS Unit02 Final

Uploaded by

r6810088
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CSS Unit02 Final

Uploaded by

r6810088
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Array,Function and String

JavaScript Array
An array is a special type of variable, which can store multiple values using special syntax.
Every value is associated with numeric index starting with 0. The following figure illustrates
how an array stores values.

JavaScript Array

Array Initialization
An array in JavaScript can be defined and initialized in two ways, array literal and Array
constructor.
a) Array Literal
Array literal syntax is simple. It takes a list of values separated by a comma and enclosed in
square brackets.

Syntax:
var array_name = [element0, element1, element2,... elementN];

The following example shows how to define and initialize an array using array literal
syntax.

Example:
var stringArray = ["one", "two", "three"];
var numericArray = [1, 2, 3, 4];
var mixedArray = [1, "two", "three", 4];

JavaScript array can store multiple element of different data types. It is not required to store
value of same data type in an array.

b) Array Constructor
You can initialize an array with Array constructor syntax using new keyword.
The Array constructor has following three forms.
Syntax:

var arrayName = new Array ( ); //creates new array with no element.

Var arrayName = new Array ( Number length ); //creates new array with specified length

Client Side Scripting (Unit 2)


Array,Function and String

Defining / Initializing Array elements


Array can be initialized in two ways:
1) Declaration and initialization can be done in one step as follow.

Syntax.

Var arrayName = new Array (element1, element2, element3, elementN); // creates new
array with elements specified in the bracket

Example:
var mixed Array = new Array(1, "two", 3, "four");

2) Array can be declared first and we can define the elements later. For this array make
use of index.

Example

var stringArray = new Array(); // Array Declaration


stringArray[0] = "one"; //Array Initialization
stringArray[1] = "two";
stringArray[2] = "three";
stringArray[3] = "four";

Array can only have numeric index (key). Index cannot be of string or any other data type.

Accessing Array Elements


An array elements (values) can be accessed using index (key). Specify an index in square bracket
with array name to access the element at particular index. Index of an array starts from zero in
JavaScript.

Example:

var stringArray = new Array("one", "two", "three", "four");

stringArray[0]; // returns "one"


stringArray[1]; // returns "two"
stringArray[2]; // returns "three"
stringArray[3]; // returns "four"

Client Side Scripting (Unit 2)


Array,Function and String

length property
Array includes “length” property which returns number of elements in the array.
Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.length; // the length of fruits is 4

Looping the Array


Use for loop to access all the elements of an array using length property.

Example: Access Array using for Loop

<script type=”text/javascript”>
var Arr = new Array("one", "two", "three", "four");
for (var i = 0; i < Arr.length ; i++)
{
document.write(Arr[i]);
}
</script>

Adding an Array Element


1. push() method
The JavaScript array push() method adds one or more elements to the end of the given array.
This method changes the length of the original array.

Syntax
The push() method is represented by the following syntax:
array.push(element1,element2 ... elementn)
Let's see some examples of push() method

Example 1
<script>
var arr=["AngularJS","Node.js"];
document.writeln("Length before invoking push(): "+arr.length+"<br>");
arr.push("JQuery","Bootstrap");
document.writeln("Length after invoking push(): "+arr.length+"<br>");
document.writeln("Update array: "+arr);
</script>

Output:

Length before invoking push(): 2


Length after invoking push(): 4
Update array: AngularJS, Node.js, JQuery, Bootstrap

Client Side Scripting (Unit 2)


Array,Function and String

2. Using length property


New element can also be added to an array using the length property:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits

Array sort() method


The JavaScript array sort() method is used to arrange the array elements in some order. By
default, sort() method follows the ascending order.
Syntax
The sort() method is represented by the following syntax:
array.sort()

Example 1
Let's see a simple example to sort the array of string elements.
<script type="text/javascript">
var fruits=["Mango","Apple","WaterMelon","Pineapple"]
var result=fruits.sort();
document.write(result)
</script>
Output:
Apple,Mango,Pineapple,WaterMelon

Numeric Sort
By default, the sort() function sorts values as strings.
This works well for strings ("Apple" comes before "Banana").
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than
"1".
Because of this, the sort() method will produce incorrect result when sorting numbers.
<script type="text/javascript">
var arr=[100,25,200,30,45]
var result=arr.sort();
document.write(result)
</script>

Output:
100,200,25,30,45

You can fix this by providing a compare function:

Client Side Scripting (Unit 2)


Array,Function and String

The Compare Function


The purpose of the compare function is to define an alternative sort order.
The compare function should return a negative, zero, or positive value, depending on the
arguments:
function (a, b)
{
return a – b
}

When the sort() function compares two values, it sends the values to the compare function,
and sorts the values according to the returned (negative, zero, positive) value.
If the result is negative a is sorted before b.
If the result is positive b is sorted before a.
If the result is 0 no changes are done with the sort order of the two values.

Example:
The compare function compares all the values in the array, two values at a time (a, b).
When comparing 40 and 100, the sort() method calls the compare function(40, 100).
The function calculates 40 - 100 (a - b), and since the result is negative (-60), the sort
function will sort 40 as a value lower than 100.

Example
Arrange the elements in ascending order using function.
<script>
var arr=[20,40,100,80,50];
var result=arr.sort(function (a,b)
{
return a-b;
});
document.writeln(result);
</script>
Output:
20,40,50,80,100

Reversing an Array
The reverse() method reverses the elements in an array. You can use it to sort an array in
descending order:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // First sort the elements of fruits
fruits.reverse(); // Then reverse the order of the elements

Client Side Scripting (Unit 2)


Array,Function and String

Example
Arrange the elements in descending order using function.
<script>
var arr=[20,40,100,80,50];
var result=arr.sort(function (a,b)
{
return b-a;
});
document.writeln(result);
</script>

Output:
100,80,50,40,20

Combining Array elements into a string:


Array join() method
The JavaScript array join() method combines all the elements of an array into a string and
return a new string. We can use any type of separators to separate given array elements.
Syntax
array.join(separator)

Separator - It is optional. It represent the separator used between array elements.


Returns a new string contains the array values with specified separator.

Example 1:
<script type="text/javascript">
var fruits=["Mango","Apple","WaterMelon","Pineapple"]
var result=fruits.join();
document.write(result)
</script>
Output:
Mango,Apple,WaterMelon,Pineapple

Example 2
In this example, we will separate the array elements using '-' separator.
<script type="text/javascript">
var fruits=["Mango","Apple","WaterMelon","Pineapple"]
var result=fruits.join('-');
document.write(result)
</script>

Client Side Scripting (Unit 2)


Array,Function and String

Array concat() Method


The JavaScript array concat() method combines two or more arrays and returns a new string.
This method doesn't make any change in the original array.

Syntax:
array.concat(arr1,arr2, ... ,arrn)

Parameter:
arr1,arr2, .. ,arrn - It represent the arrays to be combined.

Return :
A new array object that represents a joined array.

Example 1
Here, we will print the combination of two arrays.

<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>

Output:
C,C++,Python,Java,JavaScript,Android

Example 2
Here, we will print the combination of three arrays.

<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var arr3=["Ruby","Kotlin"];
var result=arr1.concat(arr2,arr3);
document.writeln(result);
</script>
Output:

C,C++,Python,Java,JavaScript,Android,Ruby,Kotlin

Client Side Scripting (Unit 2)


Array,Function and String

Array slice ( ) method


The JavaScript array slice() method extracts the part of the given array and returns it.
The slice() method selects the elements starting at the given start argument, and ends at, but
does not include, the given end argument.
This method doesn't change the original array.

Syntax
array.slice(start,end)

Parameter
start - It is optional. It represents the index from where the method starts to extract the
elements.
end - It is optional. It represents the index at where the method stops extracting elements.

Return
A new array contains the extracted elements.

Example
<script>
var arr = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var result = arr.slice(1, 3);
document.writeln(result);
</script>

Output:
Orange,Lemon

If the end argument is omitted, like in the first examples, the slice() method slices out the rest
of the array.

Example
<script>
var arr = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var result = arr.slice(1);
document.writeln(result);
</script>

Output:
Orange,Lemon,Apple,Mango

Client Side Scripting (Unit 2)


Array,Function and String

Changing Elements of Array

Array shift() method


The JavaScript array shift() method removes the first element of the given array and returns
that element. This method changes the length of the original array.
Syntax
The shift() method is represented by the following syntax:
1. array. shift()
Return
The first element of an array.
Example
<script type="text/javascript">
var fruits=["Mango","Apple","WaterMelon","Pineapple"]
var result=fruits.shift();
document.write(result)
</script>
Output:
Mango

Array pop() method


The JavaScript array pop() method removes the last element from the given array and return
that element. This method changes the length of the original array.
Syntax
array.pop()

Return
The last element of given array.
Example 1
<script type="text/javascript">

var arr=["Mango","Apple","WaterMelon","Pineapple"]
document.writeln("Orginal array: "+arr+"<br>");
document.writeln("Extracted element: "+arr.pop()+"<br>");
document.writeln("Remaining elements: "+ arr);
</script>
Output:
Original array: Mango,Apple,WaterMelon,Pineapple
Extracted element: Pineapple
Remaining elements: Mango,Apple,WaterMelon

Client Side Scripting (Unit 2)


Array,Function and String

Example 2
In this example, we will pop all the elements from the given array.

<script>
var arr=["Mango","Apple","WaterMelon","Pineapple"]
var len=arr.length;
for(var x=1;x<=len;x++)
{
document.write("Extracted element: "+arr.pop()+"<br>");
}
</script>

Output:
Extracted element: Pineapple
Extracted element: WaterMelon
Extracted element: Apple
Extracted element: Mango

The For In Loop


The JavaScript for in statement loops through the properties of an Object:

Syntax
for (key in object)
{
// code block to be executed
}

In each iteration of the loop, a key is assigned to the key variable. The loop continues for all
object properties.
Note: Once you get keys, you can easily find their corresponding values.

Example
<script type="text/javascript">
var person = {fname:"Spc", lname:"Academy", age:25}; for
(x in person)
{
document.write(x+":"+person[x]);
}
</script>

Example Explained
The for in loop iterates over a person object
In each iteration key is assigned to variable x.
These keys are used to access the value of the key.
The value of the key is person[x]

Client Side Scripting (Unit 2)


Array,Function and String

For In Over Arrays


The JavaScript for in statement can also loop over the properties of an Array:
Syntax
for (variable in array)
{
code
}

Example:
<script type="text/javascript">
var numbers = [45, 4, 9, 16, 25];
for (key in numbers)
{
document.write(key+":"+numbers[key]+"<br>"); }
</script>

Output:

0:45
1:4
2:9
3:16
4:25

Associative Array in JavaScript


Associative arrays are dynamic objects.
An Associative array is a set of key-value pairs and dynamic objects which the user modifies as
needed.
When user assigns values to keys with datatype Array, it transforms into an object and loses
the attributes and methods of Array.
It uses string instead of a number as an index.
The length attribute has no effect because the variable is no longer of Array type.
An associative array is declared or dynamically created.
We can create it by assigning a literal to a variable.

<name of the array> = { key1: 'value1', key2: 'value2', key3: 'valu3'…..}


var employee=[“Akshay”,”Saideep”,”Anushka”]

Example:
var employee = {101:"Akshay", 102:"Saideep", 103:"Anusha"}

Unlike simple arrays, here we use curly braces instead of square brackets.
This has implicitly created a variable of type Object.
The content is accessed by keys, whatever the method used to declare the array.

Client Side Scripting (Unit 2)


Array,Function and String

Example : To access numeric Keys

<script type="text/javascript">
var employee = {101:"Akshay", 102:"Saideep", 103:"Anusha"}
var x = employee[101];
document.write(x);
</script>

Example: To access string keys


<script type="text/javascript">
var employee = {"one":"Akshay", "two":"Saideep", "three":"Anusha"}
var x = employee["one"];
document.write(x);
</script>

An associative array is also an object


So we can create an associative array with the Object reserved word, then and assign keys and
values:

<script type="text/javascript">
var employee = new Object();
employee["one"] = "Akshay";
employee["two"] = "Sai";
employee["three"] = "Amol";
for(var i in employee)
{
document.write(i + "=" + employee[i] + '<br>');
}
</script>

Attributes of a JavaScript object are also keys


What is specific to objects in JavaScript is that attributes are also keys as we shall see in the
demonstration.
Thus, the same array can be created more simply:

<script type="text/javascript">
var employee = new Object();
employee.one = "Akshay";
employee.two = "Sai";
employee.three = "Amol";
for(var i in employee)
{
document.write(i + "=" + employee[i] + '<br>');
}
</script>

Client Side Scripting (Unit 2)


Array,Function and String

Function
 A function is a group of statements that perform specific tasks.
 We can write the functions in the JavaScript for bringing the modularity in the script.
 Separate functions can be created for each separate task.

Defining a Function
 We can define the function anywhere in the script either in head or body section or in both.
But it is standard practice to define the function in the head section and call that function
from the body section
 The declaration of a function start with the function keyword, followed by the name of the
function you want to create, followed by parentheses i.e. ( ) and finally place your function's
code between curly brackets {}.

Syntax for declaring a function without arguments:

function functionName( )
{
// Code to be executed
}

Example:
// Defining function
function sayHello( )
{
alert("Hello, welcome to Spc!");
}

Note: A function name must start with a letter or underscore character not with a number,
optionally followed by the more letters, numbers, or underscore characters. Function names are
case sensitive, just like variable names.

Adding Parameters to Functions


You can specify parameters when you define your function to accept input values at run time.
The parameters work like placeholder variables within a function; they're replaced at run time
by the values (known as argument) provided to the function at the time of invocation.
Parameters are set on the first line of the function inside the set of parentheses, like this:

function functionName(parameter1, parameter2, parameter3)


{
// Code to be executed
}
1. Function with return_value and with no parameters
2. Function with return_value and with parameter
3. Function with no return_value and with no parameters
4. Function with no return_value and with parameters

Client Side Scripting (Unit 2)


Array,Function and String

Example
The displaySum() function in the following example takes two numbers as arguments, simply
add them together and then display the result in the browser.

// Defining function
function displaySum (num1, num2)
{
var total = num1 + num2;
alert(total);
}

// Calling function
displaySum(6, 20); // 0utputs: 26
displaySum(-5, 17); // 0utputs: 12

Calling a Function
Defining a function does not execute it. Defining it simply names the function and specifies
what to do when the function is called.
Once a function is defined it can be called (invoked) from anywhere in the document, by typing
its name followed by a set of parentheses.
Syntax: functionName( );

A] Calling a Function without an Argument


A function is called without passing any argument. In this case, all the required variables are
declared and used within that function. Following program shows how to call a function without
passing an argument.
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function add()
{
var a = 10;
var b = 20;
c=a+b
document.write("Addition "+c)
}
</script>
</head>
<body>
<script type = "text/javascript">
add()
</script>

</body>
</html>

Client Side Scripting (Unit 2)


Array,Function and String

B] Calling a Function with Argument


In JavaScript, we can pass an argument to the function. Following JavaScript shows how to
pass an argument to the function. In the following program I have written a simple function for
addition of two numbers. The values of two numbers are 10 and 20 respectively. Inside this
function the addition of these two arguments is carried out and result is displayed on the
Browser page.
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function add(a,b)
{
c=a+b
document.write("Addition "+c)
}
</script>
</head>
<body>
<script type = "text/javascript">
add(30,20);
</script>
</body>
</html>

C] Calling Function from HTML

For calling a function from HTML normally, JavaScript events are used. For example the function
will be called in response to an event such as web page is loaded or unloaded by the browser.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">

function sum() //function definition


{
var a=10,b=20;
var tot=a+b;
alert("Total is" + tot)
}
</script>
</head>

<body onload= "sum()">


</body>
</html>

Client Side Scripting (Unit 2)


Array,Function and String

D] Function Calling another Function


We can call one function from another function. This is called nested functions. In the following
code, there is a call for function difference() from function sum().
<!DOCTYPE html>
<html>
<head>
<title></title>

<script type="text/javascript">

function sum(a,b)
{
var tot = a+b;
document.write("Total is" + tot)
difference(a,b);
}
function difference(a,b)
{
var result = a-b;
document.write("<br>Difference is" + result)

}
</script>
</head>
<body>
<script type="text/javascript">
sum(50,34);
</script>
</body>
</html>

Returning Values from a Function


A function can return a value back to the script that called the function as a result using the
return statement. The value may be of any type, including arrays and objects.

The return statement usually placed as the last line of the function before the closing curly
bracket and ends it with a semicolon, as shown in the following example.

Example
function sum(a, b)
{
return a + b;
}

var result = sum(1, 2);


alert( result );

Client Side Scripting (Unit 2)


Array,Function and String

Scope of Variable and Argument


 Scope is the block or area of program in which particular variable or argument is accessible.
 The scope is defined using two types of variables - Local Scope and Global Scope.
.
Local Scope
If a variable is defined inside a function then that variable is a local variable and its scope is a
local scope. That also means, that the local variable is accessible only within a function in
which it is defined. It is not accessible outside that function.
Following program shows the use of local variable.
JavaScript Example for Demonstrating scope of Local Variable

<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function A()
{
var a =100 //local variable
document.write ("from function A (): a is" + a)
}
function B()
{
document.write ("from function B (): a is" + a) // variable a is not accessible
}
</script>
</head>
<body>
<script type = "text/javascript">
A( )
B( )
</script>
</body>
</html>
Output:
from function A (): a is100

Explanation:
(1) We have created two functions namely A() and B().
(2) Inside the A() function variable ‘a’ is declared and initialized to the value 100. The value of
this variable is displayed. Here variable ‘a’ is accessible.
(3) Inside the B() function, we are trying to display the value of same variable a. But the output
does not display value of variable ‘a’ through function B(). This is because variable a is a local
variable declared in function A(). Hence its scope is upto the function A(). Outside this function,
the variable a is not accessible.

Client Side Scripting (Unit 2)


Array,Function and String

Global Variable
A variable is called global variable, if it is defined outside the function. The variable having
global scope is accessible by any function.
Following example illustrates the use of global variable.
JavaScript Example for Demonstrating the scope of Global Variable
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
var a =100//global variable
function A()

{
document.write ("from function A (): a is" + a)
}
function B()
{
document.write ("<br> from function B (): a is" + a)
}
</script>
</head>
<body>

<script type = "text/javascript">


A( )
B( )
</script>
</body>
</html>
Output
from function A (): a is100
from function B (): a is100

Client Side Scripting (Unit 2)


Array,Function and String

JavaScript String
The JavaScript string is an object that represents a sequence of characters.
JavaScript strings are used for storing and manipulating text.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)

1) By string literal
The string literal is created using double quotes.
syntax:
var stringname="string value";
Let's see the simple example of creating string literal.
<script>
var str="This is string literal";
document.write(str);
</script>
Output:
This is string literal

2) By string object (using new keyword)


Syntax:
var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
Example:
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
Output:
hello javascript string

Client Side Scripting (Unit 2)


Array,Function and String

JavaScript String Methods


Manipulating a String
Manipulating a string means, changing one string to another, joining two strings, changing the
string from upper case to lower case or from lower case to upper
There are some commonly used methods of string

Methods Description

charAt() It provides the char value present at the specified index.

charCodeAt() It provides the Unicode value of a character present at the specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

It provides the position of a char value present in the given string by


lastIndexOf()
searching a character from the last position.

It searches a specified regular expression in a given string and returns its


search()
position if a match occurs.

replace() It replaces a given string with the specified replacement.

It is used to fetch the part of the given string on the basis of the specified
substr()
starting position and length.

It is used to fetch the part of the given string on the basis of the specified
substring()
index.

It is used to fetch the part of the given string. It allows us to assign positive
slice()
as well negative index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase It converts the given string into lowercase letter on the basis of host?s
() current locale.

toUpperCase() It converts the given string into uppercase letter.

toLocaleUpperCase It converts the given string into uppercase letter on the basis of host?s
() current locale.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

It splits a string into substring array, then returns that newly created
split()
array.

trim() It trims the white space from the left and right side of the string.

Client Side Scripting (Unit 2)


Array,Function and String

 Joining a String
1) using + operator.
For Example
<!DOCTYPE html>
<html>
<script type = "text/javascript">
var firstName="AAA"
var lastName="BBB"
var name=firstName+lastName
alert(name);
</script>
<body>
</body>
</html>
Output: AAABBB

2) using concat() Method


The JavaScript string concat() method combines two or more strings and returns a new
string. This method doesn't make any change in the original string.

Syntax
string.concat(str1,str2,...,strn)
Parameter
str1,str2,...,strn - It represent the strings to be combined.
Return
Combination of strings.
Example 1:
<script>
var x="Spc";
var y=".com";
var z=" Tutorials";

</script>
Output:
Javatpoint.com Tutorials

Client Side Scripting (Unit 2)


Array,Function and String

 Retrieving character from given Position:


charAt() Method
The JavaScript string charAt() method is used to find out a character present at the specified
index in a string.
The index number starts from 0 and goes to n-1, where n is the length of the string.
Syntax
String.charAt(index)
Parameter
index - It represent the position of a character.
Returns
A char value
Example 1
<script>
var str="Javatpoint";
document.writeln(str.charAt(4));
</script>
Output:
t

Example 2
<script>
var str="Javatpoint";
document.writeln(str.charAt()); //print first character
</script>
Output:
J

 Findig a Unicode of a character:


charCodeAt() Method
A computer can understand only numbers and characters.
Unicode is a standard that assigns a number to every character, number and symbol.
The JavaScript string charCodeAt() method is used to find out the Unicode value of a
character at the specific index in a string.

The index number starts from 0 and goes to n-1, where n is the length of the string. It returns
NaN if the given index number is either a negative number or it is greater than or equal to the
length of the string.
Syntax
string.charCodeAt(index)
Parameter
index - It represent the position of a character.
Return
A Unicode value

Client Side Scripting (Unit 2)


Array,Function and String

Example 1
<script>
var x="Javatpoint";
document.writeln(x.charCodeAt(3));
</script>
Output:
97

Example 2
In this example, we will not pass any index number with the method. In such case, it will
return the Unicode value of first character.
<script>
var x="Javatpoint";
document.writeln(x.charCodeAt());//It will return Unicode value of 'J'
</script>
Output:
74

 Retrieving a Position of character in given String:


1) indexOf() method
The JavaScript string indexOf() method is used to search the position of a particular
character or string in a sequence of given char values. This method is case-sensitive.
The index position of first character in a string is always starts with zero. If an element is not
present in a string, it returns -1.

Syntax
indexOf(ch,index)
It start searching the element from the provided index value and then returns the index
position of specified char value.
index - It is optional which represent the index position from where search starts.

Example 1
Here, we will print the position of a single character.

<script>
var web="Learn JavaScript on Javatpoint";
document.write(web.indexOf('a'));
</script>
Output:
2

Client Side Scripting (Unit 2)


Array,Function and String

Example 2
In this example, we will provide the index value from where the search starts.

<script>
var web="Learn JavaScript on Javatpoint";
document.write(web.indexOf('a',3));
</script>
Output:
7

2) search() Method
The JavaScript string search() method is used to search the regular expression in the given
string. This method returns -1, if match is not found.

Syntax
string.search(regexp)
Parameter
regexp - It represents the regular expression which is to be searched.
Return
The position of searched character.

Example:
<script>
var str="JavaScript is a scripting language. Scripting languages are often interpreted";
document.writeln(str.search("scripting"));
</script>
Output:
16

 Copying a substring
1) 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
start - It represents the position of the string from where the fetching starts.
length - It is optional. It represents the number of characters to fetch.
Return: Part of the string.

Client Side Scripting (Unit 2)


Array,Function and String

Example:
<script>
var str="Javatpoint";
document.writeln(str.substr(0,4));
</script>

Output:
Java

2) 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.
Return: Part of the string.
Example
<script>
var str="Javatpoint";
document.writeln(str.substring(0,4));
</script>
Output:
Java

3) JavaScript String slice() Method

The JavaScript string slice () method is used to fetch the part of the string and returns the new
string. It is required to specify the index number as the start and end parameters to fetch the
part of the string. The index starts from 0. It allows us to assign positive as well negative index.

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.
Return
Part of the string

Client Side Scripting (Unit 2)


Array,Function and String

Example 1
Here, we will print the part of the string by passing starting and ending index.

<script>
var str = "SpcAcademy";
document.writeln(str.slice(2,5));
</script>

Output:
row

Example 2
Here, we will provide starting index only. In such case, the method fetches the string up to its
length.

<script>
var str = "SpcAcademy";
document.writeln(str.slice(4));
</script>
Output:
wAcademy

Example 3
In this example, we will provide negative number as an index. In such case, the method starts
fetching from the end of the string.
<script>
var str = "SpcAcademy";
document.writeln(str.slice(-5));
</script>

Output:
ademy

Convert a string into integer


To convert a string to an integer parseInt() function is used in javascript. parseInt() function
returns NaN( not a number) when the string doesn’t contain number.
If a string with a number is sent then only that number will be returned as the output.
This function won't accept spaces.
If any particular number with spaces is sent then the part of the number that presents before
space will be returned as the output.

syntax
parseInt(value);
This function takes a string and converts it into an integer. If there is no integer present in the
string, NaN will be the output.

Client Side Scripting (Unit 2)


Array,Function and String

Example
In the following example, various cases of strings such as only strings, strings with
numbers, etc have been taken and sent through the parseInt() function. Later on, their
integer values, if present, have displayed as shown in the output.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<script>
var a = "10";
document.write("value is " + parseInt(a)+"<br>");
var b = "420-23-567";
document.write('value is ' + parseInt(b)+"<br>");
var c = "string";
document.write("value is " + parseInt(c)+"<br>");
var d = "2String"
document.write("value is " + parseInt(d)+"<br>");
</script>
</head>
<body>
</body>
</html>

Output
value is 10
value is 420
value is NaN
value is 2

Client Side Scripting (Unit 2)


Array,Function and String

 Changing case of String


1) toLowerCase() Method
The JavaScript string toLowerCase() method is used to convert the string into lowercase
letter. This method doesn't make any change in the original string.
Syntax
string.toLowerCase()
Return
String in lowercase letter.
Example 1
<script>
var str = "SPCACADEMY";
document.writeln(str.toLowerCase());
</script>

Output:
Spcacademy

2) toUpperCase() Method
The JavaScript string toUpperCase() method is used to convert the string into uppercase letter.
This method doesn't make any change in the original string.

Syntax
string.toUpperCase()
Return
String in uppercase letter.
Example
<script>
var str = "javatpoint";
document.writeln(str.toUpperCase());
</script>
Output:
JAVATPOINT

Client Side Scripting (Unit 2)


Array,Function and String

 Dividing Text

String split()
As the name implies, the split() method in JavaScript splits the string into the array of
substrings, puts these substrings into an array, and returns the new array. It does not change
the original string.

Syntax
string.split(separator, limit)

separator: It is an optional parameter. It specifies the point where the split should take place.
If it has multiple characters, then the sequence of the entire character must be found to split.

If the separator is not present in the given string, or if it is omitted, then the entire string
becomes a single array element. In these cases, the returned array contains a single element
consisting of the entire string.

If the separator is present at the beginning or the end of the string, then it still has the effect of
splitting. The returned array consists of an empty string of zero length that appears at the
beginning or the last position of the returned array.

limit: It is also an optional parameter. It is a non-negative integer that specifies the number of
limits. It defines the higher limit on the number of splits to be found in the given string. If it is
given, it splits the string at each occurrence of the specified separator. It stops when the limit
entries have been placed in the array.

An array can contain fewer entries than the given limit. It happens when the end of the string
is reached before the limit is reached.

Let's understand the split() method using some examples.

Example1
In this example, the split() function splits the string str wherever the whitespace (" ") occurs and
returns an array of strings. Here, we are using the limit argument and providing the value of the
limit argument to 3.

<script>
var str = 'Welcome to the Spc Computer Academy'
var arr = str.split(" ", 3);
document.write(arr);
</script>

Output
Welcome,to,the

Client Side Scripting (Unit 2)


Array,Function and String

Example2
In this example, we are using the letter 't' as the separator of the given string. The split() function
will make an array of strings by splitting the given string at each occurrence of the letter 't'.
Here, we are not specifying the limit argument.z

<script>
var str = 'Welcome to the Spc Academy'
var arr = str.split("t");
document.write(arr);
</script>
Output
Welcome ,o ,he Spc Academy

Example 3
In this example, we are omitting the separator parameter. In the output, we can see that the
returned array contains a single element consists of the given string.

<script>
var str = "Welcome to the Spc Academy"
var arr = str.split();
document.write(arr);
</script>

Output
Welcome to the Spc Academy

Client Side Scripting (Unit 2)

You might also like