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

CSS Unit2 Notes

This document discusses arrays in JavaScript. It defines arrays as collections of elements that can be of the same type. Arrays are declared using the var keyword and Array constructor. Elements are accessed using the array name and index. Methods like sort(), join(), concat() can manipulate array elements. Other methods like push(), pop(), shift(), unshift() can add/remove elements from the array.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

CSS Unit2 Notes

This document discusses arrays in JavaScript. It defines arrays as collections of elements that can be of the same type. Arrays are declared using the var keyword and Array constructor. Elements are accessed using the array name and index. Methods like sort(), join(), concat() can manipulate array elements. Other methods like push(), pop(), shift(), unshift() can add/remove elements from the array.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Unit 2: Arrays, Functions and Strings

2.1 Array
An array can comprise one or multiple elements of
same type.
Each element is like a variable in that an array
element refers to a memory location where
information can be temporarily stored.
An array is identifi edby a unique name, similar to
the name of a variable.
A number called an index identifies an array element.
The combination of the array name and an index is
nearly the same as a variable name.
In your JavaScript, you use both the array name and
the index to specify a particular memory location.
Declaring an Array
You create an array by writing a declaration
statement in your JavaScript, which is very similar to
the way you declared a variable. This declaration
statement has five parts:
The first part is the var keyword;
The second part is the array name, which you create;
The third part is the assignment operator(=);
The fourth part is the new operator;
and the fifth part is the Array() constructor.
All these parts are shown here:
Syntax:
var Array_name = new Array()
e.g.
var products = new Array()
Initializing an Array
Initialization is the process of assigning a value when
either a variable or an array is declared.
When initializing an array, you place the value within
the parentheses of the Array() constructor.
Syntax:
var Array_name=new Array(Value1,Value2,.......Valuen)
e.g.
var products = new Array('Burger', 'Water', 'Pizza', 'Bread')

Initializing an Array
Notice the following:
Each value is placed within the parentheses of
the Array() constructor.
Values must be the same type of information.
This can be a string, number, Boolean, and
object types.
The preceding code segment uses strings ('Burger',
'Water', 'Pizza', 'Bread').
JavaScript won’t let us use a mixture of types; all of
the values must be the same type.
A comma must separate each value.

Defining an Array Elements:


Think of an array as a list containing the same kinds
of things—such as a list of product names or a list of
customer first names.
Each item on the list is identified by the number in
which the item appears on the list.
The first item is number 0, the second item is
number 1, then 2, and so on.
To assign a product name to an array element, you
must specify the name of the array followed by the
index of the array element.
The index must be enclosed within square brackets.
e.g.
var products = new Array('Burger', 'Water', 'Pizza',
'Bread')
In this example, products is the name of the array,
and 0 is the index of the first element of the array.

Defining an Array Elements:


products[0] = 'Burger'
products[1] = 'Water'
products[1] = 'Pizza'
products[1] = 'Bread'
Hence we use the array element (array name plus
the index) to tell the browser that you want to use
the value that is associated with the array element.
This is the same as using the variable name to tell the
browser that you want to use the value that is
associated with the variable:
e.g. document.write(products[0])

Looping the Array:


The major advantages of using an array over a
variable, except that you can use the same name for
each element of the array. The power of using an
array is evident when you need to process each
element of the array.
Suppose you need to display all the array elements
on a document.
If you use four variables—one for each product—
you’ll have to write the document.write() method in
four different statements within your JavaScript.
But if you use an array, you’ll have to write the
document.write() method in only one statement.
e.g.
for (var i = 0; i < products.length; i++)
{
document.write(products[i]+’<br>’)
}

The loop begins by initializing variable i to the value 0.


Remember that the value of the length property is 4
because there are four elements in the products
array.
Since the value of i is less than 4, the browser
executes the statement within the loop.
The browser replaces the i with the current value of
the variable i.
Therefore, the browser writes the value of array
element 0.
The browser returns to the top of the for loop and
increments (i++) the value of i, making its value 1.
The browser evaluates the conditional expression
and determines whether or not to execute the
statement within the for loop again. It decides to
execute the statement.

Adding an Array Element:


How do you know what index to assign to the new
array element?
The solution is to use the length property of the
array, as illustrated here:
products[products.length] = 'chips'
Remember from the previous section that the
products array has four array elements. Therefore,
the value of the length property of the array is 4.
This means that the value 'chips' is assigned to the
products[4] element.
Now there are five elements in the array.

Sorting Array Elements:


The index of the array elements determines the
order in which values appear in an array when a for
loop is used to display the array.
Sometimes you want values to appear in sorted
order, which means that strings will be presented
alphabetically and numbers will be displayed in
ascending order.
You can place an array in sorted order by calling the
sort() method of the array object.
The sort() method reorders values assigned to
elements of the array, regardless of the index of the
element to which the value is assigned.
Sorting Array Elements:
e.g.
var products = new Array('Burger', 'Water', 'Pizza',
'Bread')
products.sort()
for (var i = 0; i < products.length; i++)
{
document.write(products[i] + '<br>')
}

Combining Array Elements into a String:


At some point, you’ll want to combine values of the
array element into one string.The following array
illustrates:
products[0] = 'Soda '
products[1] = 'Water'
products[2] = 'Pizza'
products[3] = 'Beer'
Each array element contains a product name. By
combining the array elements,
We create a string that looks like this:
'Soda,Water,Pizza,Beer'
Once the product names are combined into a string,
we can display the string on adocument or on a
JavaScript form.
Array elements can be combined in two ways: by
using the concat() method or the join() method of
the array object. Both of these methods do
practically the same thing—that is, they concatenate
copies of values of array elements.
Values of these elements remain untouched in the
array.
However, there is a subtle difference between the
concat() method and the join() method.
The concat() method separates each value with a
comma. The join() method also uses a comma to
separate values, but you can specify a character
other than a comma to separate values.
You do this by placing that character in the
parentheses of the join() method.

Array elements can be combined in two ways: by


using the concat() method or the join() method of
the array object. Both of these methods do
practically the same thing—that is, they concatenate
copies of values of array elements.
Values of these elements remain untouched in the
array.
However, there is a subtle difference between the
concat() method and the join() method.
The concat() method separates each value with a
comma. The join() method also uses a comma to
separate values, but you can specify a character
other than a comma to separate values.
You do this by placing that character in the
parentheses of the join() method.

var str = products.concat()


The value of str is:
'Soda,Water,Pizza,Beer'
Here’s how to use the join() method.
In this example, we use a space to separate values:
var str = products.join(' ')
The value of str in this case is:
'Soda Water Pizza Beer'
Changing Elements of the Array:
The shift() method
The shift() method removes and returns the first
element of the array and then moves the other tasks
up on the list.
Here’s how to call the shift() method:
e.g.
var ToDoList = new Array()
ToDoList[0] = "Book the Waldorf for your birthday
party."
ToDoList[1] = "Give the Donald a call”
ToDoList[2] = "Leave word at the White House”
var task = ToDoList.shift()
Here’s the ToDoList array after the shift() method is
called:
ToDoList[0] = "Give the Donald a call”
ToDoList[1] = "Leave word at the White House”
The push() method
The push() method of the array object to place a new
task at the end of the to-do list.
You place the task that you want placed on the to-do
list between
the parentheses of the push() method, as shown
here:
e.g.
ToDoList.push("Wake up from your dream.")
The push() method creates a new element at the end
of the array and assigns the value that you place
between the parentheses of the new element.
Here’s what the array looks like after calling the
push() method:
ToDoList[0] = "Give the Donald a call and invite him
to your party."
ToDoList[1] = "Leave word at the White House that
you won't be available for dinner."
ToDoList[2] = "Wake up from your dream."

The reverse() method


The reverse() method to reverse the order of values
in the array.
Here’s how you call the reverse() method:
e.g.
ToDoList.reverse()
And here’s how the ToDoList array looks after the
reverse() method is called:
ToDoList[0] = "Wake up from your dream."
ToDoList[1] = "Leave word at the White House that
you won't be available for dinner."
ToDoList[2] = "Give the Donald a call and invite him
to your party."
The pop() method
The pop() method returns and removes the last
element of the array. Here’s how this is done:
var task = ToDoList.pop()
Here’s the array after the pop() method is called:
ToDoList[0] = "Wake up from your dream."
ToDoList[1] = "Leave word at the White House that
you won't be available for dinner."

Slice() method:Making a New Array from an Existing Array


The slice() method copies a sequential number of array
elements from one array into a new array.
This means values of these elements exist in both arrays.
The slice() method has two arguments, which tell the slice()
method which elements should be copied into the new
array.
The first element tells the method where to start copying,
and the second element tells the method where to end. The
second argument is the element immediately after the last
element to copy.
Array elements are identified by the index of the element.
<!DOCTYPE html>
<html>
<head>
<title>Display Array Elements Using Slice()</title>
</head>
<body>
<script language="Javascript" type="text/javascript">
var fruits=new Array()
fruits[0]='Mango'
fruits[1]='Apple'
fruits[2]='Strawberry'
fruits[3]='Grapes'
fruits[4]='Berry'
fruits[5]='Watermelon'
fruits[6]='Pineapple'

var PartialList=fruits.slice(2,5)
for (var i = 0;i<PartialPhoneList.length;i++)
{
document.write(PartialList[i] + '<br>')
}
</script>
</body>
</html>
2.2 Function
A function performs an action when you call the
function in a JavaScript—such as when you called the
alert() function to display a message on the screen.
Two kinds of functions are used in JavaScript:
predefined functions and custom functions.
A predefined function is already created for you in
JavaScript, such as the alert() function.
A custom function is a function that you create.

• Think of a function as part of your JavaScript that


has a name and contains one or more statements.
• You name the function and write the statement(s)
that are contained within the function.
• You then use the name of the function elsewhere
in your JavaScript whenever you want the browser
to execute those statements.
• A function can be called from anywhere in the
JavaScript file or in the HTML document.
• The process of creating a function is called defining
a function.
• The process of using the function is referred to as
calling a function.

Defining a Function
• A function must be defined before it can be called
in a JavaScript statement.
• If you think about it, this makes sense, because the
browser must learn the definition of the word (the
function name) before the browser sees the word
(the function call) in a statement.
• The best place to define a function is at the
beginning of a JavaScript that is inserted in the
<head> tag, because then all subsequent
JavaScripts on the web page will know the
definition of that function.
• The browser always loads everything in the <head>
tag before it starts executing any JavaScript.
A function definition consists of four parts: the name,
parentheses, a code block, and an optional return
keyword.
• Function Name
• The function name is the name that you’ve
assigned the function. It is placed at the top of the
function definition and to the left of the
parentheses.
• Any name will do, as long as it follows certain
naming rules. The name must be
• • Letter(s), digit(s), or underscore character
• • Unique to JavaScripts on your web page, as no
two functions can have the same name.
• The name cannot
• • Begin with a digit.
• • Be a keyword.
• • Be a reserved word.
• The name should be
• • Representative of the action taken by statements
within the function.
• Parentheses
• Parentheses are placed to the right of the function
name at the top of the function definition.
• Parentheses are used to pass values to the function;
these values are called arguments.
• Code Block
• The code block is the part of the function defi
nition where you insert JavaScript statements that
are executed when the function is called by
another part of your JavaScript application.
• Open and close French braces define the
boundaries of the
• code block.
• Statements that you want executed must appear
between the open and close French braces.

• Return (Optional)
• The return keyword tells the browser to return a
value from the function definition to the statement
that called the function.
• Not all functions return a value.
• For example, a function that displays a message on
the screen doesn’t need to return a value to the
statement that calls the function.
• Therefore, the return keyword doesn’t need to be
included in the function definition.

• e.g.
function IncreaseSalary()
{
var salary = 500000 * 1.25
alert("Your new salary is " + salary)
}

Adding Arguments
• A function typically needs data to perform its task.
• Sometimes you provide the data when you define
the function, such as the salary and percentage
increase in salary in the preceding example.
• Other times, the data is known only when you run
your JavaScript.
• An argument is one or more variables that are
declared within the parentheses of a function
definition.
• This is illustrated in the following code sample.
• OldSalary is an argument of the IncreaseSalary()
function.
function IncreaseSalary(OldSalary)
{
var NewSalary = OldSalary * 1.25
alert("Your new salary is " + NewSalary)
}
• The JavaScript statement or the HTML code
provides the value when it calls the function. This is
called passing a value to the function.
• Think of an argument as a variable, which you
learned about .
• You assign a name to an argument following the
same rules that apply to naming a variable.
• Anything you can do with a variable you can do
with an argument.
• You might be wondering how an argument is
assigned a value. This happens when the function
is called either by a statement within the JavaScript
or by HTML code on your web page.
Adding multiple Arguments
• You can use as many arguments as necessary for
the function to carry out its task.
• Each argument must have a unique name, and
each argument within the parentheses must be
separated by a comma.
• e.g.
function IncreaseSalary(OldSalary, PercIncrease)
{
var NewSalary = OldSalary * (1 + (PercIncrease / 100))
alert("Your new salary is " + NewSalary)
}

The Scope of Variables and Arguments


• A variable can be declared within a function, such
as the NewSalary variable in the IncreaseSalary()
function.
• This is called a local variable, because the variable
is local to the function.
• Other parts of your JavaScript don’t know that the
local variable exists because it’s not available
outside the function.
• But a variable can be declared outside a function.
• Such a variable is called a global variable because
it is available to all parts of your JavaScript—that is,
statements within any function and statements
outside the function can use a global variable.

Calling a Function
• A function is called by using the function name
followed by parentheses.
• If the function has arguments, values for each
argument are placed within the parentheses.
• You must place these values in the same order that
the arguments are listed in the function definition.
• A comma must separate each value.
• Here’s how the IncreaseSalary() function is called:
• e.g.
IncreaseSalary(500000, 6)

Calling a Function without argument


<!DOCTYPE html >
<html>
<head>
<title>Functions</title>
<script language="Javascript" type="text/javascript">
<!--
function IncreaseSalary()
{
var salary = 500000 * 1.25
alert('Your new salary is ' + salary)
}
-->
</script>
</head>
<body>
<script language="Javascript" type="text/javascript">
<!--
IncreaseSalary()
-->
</script>
</body>
</html>
Calling a Function with argument
<!DOCTYPE html>
<html>
<head>
<title>Functions</title>
<script language="Javascript" type="text/javascript">
<!--
function IncreaseSalary(OldSalary, PercIncrease)
{
var NewSalary= OldSalary * (1 + (PercIncrease / 100))

alert("Your new salary is " + NewSalary)


}
-->
</script>
</head>
<body>
<script language="Javascript" type="text/javascript">
<!--
var Salary = prompt('Enter old salary.', ' ')
var Increase=prompt('Enter salary increase as percent.', ' ')

IncreaseSalary(Salary, Increase)
-->
</script>
</body>
</html>
Calling a Function from HTML
• A function can be called from HTML code on your
web page. Typically, a function will be called in
response to an event, such as when the web page
is loaded or unloaded by the browser.
• You call the function from HTML code nearly the
same way as the function is called from within a
JavaScript, except in HTML code you assign the
function call as a value of an HTML tag attribute.
Let’s say that you want to call a function when the
browser loads the web page. Here’s what you’d
write in the <body> tag of the web page:
<body onload = "WelcomeMessage()">
• Here’s what you’d write to call the function right
before the user moves on to another web page:
<body onunload = "GoodbyeMessage()">

Calling a Function from HTML


<!DOCTYPE>
<html>
<head>
<title>Calling a function from HTML</title>
<script language="Javascript" type="text/javascript">
<!--
function WelcomeMessage()
{
alert('Glad to see you.')
}

function GoodbyeMessage()
{
alert('So long.')
}
-->
</script>
</head>
<body onload="WelcomeMessage()" onunload="GoodbyeMessage()">

</body>
</html>
Creating a Popup Window
• Popup windows are probably the most annoying
things on the Internet.
• You surf to a web site only to be shown a popup ad,
and then when you leave the site you’re shown
another popup ad.
• Nevertheless, popups can be a necessary evil when
you’re creating web sites.
• You can create a function that displays a popup
window that you design on the fly.
• The new window is opened by calling the
window.open() method of the window object.

e.g.
<!DOCTYPE html >
<html>
<head>
<title>Calling a function from HTML</title>
<script language="Javascript" type="text/javascript">
<!--
function WelcomePopup()
{
window.open();
alert('Glad to see you.')
}
function GoodbyePopup()
{
window.open();
alert('So long.')
}
-->
</script>
</head>
<body onload="WelcomePopup()" onunload="GoodbyePopup()">

</body>
</html>

Functions Calling Another Function


• JavaScript developers typically divide an
application into many functions, each of which
handles a portion of the application.
• Functions can be called from any JavaScript or from
HTML code on a web page itself.
• This means that a function can also be called from
another function.
• Let’s say that you defined a logon function that
handles all the tasks that are necessary for a user
to log on to your application.
• This includes displaying dialog boxes prompting the
user to enter a user ID and password.

Functions Calling Another Function


• Let’s also say that you defi ned another function
whose only tasks are to validate a user ID and
password and report back whether or not the
logon information is valid.
• The logon function passes the user ID and
password to the validation function and then waits
for the validation function to signal whether or not
they are valid.
• The logon function then proceeds by telling the
user whether the logon is valid or not valid.

Returning Values from a Function


• A function can be designed to do something and
then report back to the statement that calls after
it’s fi nished—such as the validation function,
which validates a user ID and password and then
reports back whether they are valid or not.
• A function reports back to the statement that calls
the function by returning a value to that statement
using the return keyword, followed by a return
value in a statement.
• Here’s what this looks like:
function name ()
{
return value
}
• In given code segment, the return statement
returns a Boolean value true.
• You can return any value or variable in a return
statement.
• The return value is typically assigned to a variable
by the statement that called the function and then
used by other statements in the JavaScript.
• This is illustrated in the following code segment:
valid = ValidateLogon('ScubaBob', 'diving')
• This statement calls the ValidateLogon() and passes
it a user ID (the fi rst argument) and password (the
second argument).
The return value, which in this example is either true
or false, is then assigned to the valid variable.
e.g.
<!DOCTYPE html >
<html>
<head>
<title>Returning a value from a function</title>
<script language="Javascript" type="text/javascript">
<!--
function Logon()
{
var userID
var password
var valid
userID = prompt('Enter user ID',' ')
password = prompt('Enter password',' ')
valid = ValidateLogon(userID, password)
if ( valid == true)
{
alert('Valid Logon')
}
else
{
alert('Invalid Logon')
}
}
function ValidateLogon(id,pwd)
{
var ReturnValue
if(id == 'ScubaBob' && pwd == 'diving')
{
ReturnValue = true
}
else
{
ReturnValue = false
}
return ReturnValue
}
-->
</script>
</head>
<body>
<script language="Javascript" type="text/javascript">
<!--
Logon()
-->
</script>
</body>
</html>

2.4 String
• A string is a series of characters that form text.
• It is often necessary to take apart and rearrange
text so that the information can be processed
properly. This is referred to as manipulating a
string
Why Manipulate a String?
• Text, to most of us, is a series of words, such as
Bob Smith, which is a customer name.
• However, commercial applications don’t use text.
• Instead, they use data, which is defined as the
smallest available amount of meaningful
information.
• 'Bob Smith' is a text string, since the words are
enclosed in quotation marks.
• You can recognize this string as a person’s name.
• The person’s name can be divided into two pieces
of data, commonly referred to as data elements.
• These are first name and last name, which are the
smallest amount of meaningful information in the
text string of a person’s name.
• Text must be transformed into data elements if
information gathered by your application is to be
stored in a database, which is like an electronic
filing cabinet for pieces of data.
• Commercial applications store a person’s first
name('Bob')
• and last name('Smith') separately, rather than the
full name ('Bob Smith') in the database.
• This means you must write statements that divide
'Bob Smith' into 'Bob' and 'Smith'. This is called
manipulating a string.

Joining String
(string manipulation by concatenating two strings)

• When you concatenate a string, you form a new


string from two strings by placing a copy of the
second string behind a copy of the fi rst string.
• The new string contains all the characters from
both the
• first and second strings.
• You use the concatenation operator (+) to
concatenate two strings, as shown here
• (note that, in this context, + is the concatenation
operator, not the addition operator):
• NewString = FirstString + SecondString
• Suppose you needed to display a customer’s full
name on the screen.
• However, the customer’s name is stored in the
database as two data elements called FirstName
and LastName.
• You’ll need to concatenate the first name and the
last name into a new string and then display the
new string on the screen.
Joining String:Example
<!DOCTYPE html>
<html>
<head>
<title>Concatenating a string</title>
</head>
<body>
<script language="Javascript" type="text/javascript">
<!--
var newString = 'Bob' + 'Smith'
alert(newString)
-->
</script>
</body>
</html>

Joining String:Example 2
<!DOCTYPE html>
<html>
<head>
<title>Concatenating a string</title>
</head>
<body>
<script language="Javascript" type="text/javascript">
<!--
var FirstName = 'Bob'
var LastName = 'Smith'
var space = ' '
var newString = FirstName + space + LastName
alert(newString)
-->
</script>
</body>
</html>
Retrieving a character from given position
• Each character in a string is an array element that
can be identified by its index.
• var FirstName = 'Bob'
• You can copy a character from a string to another
string by using the charAt() method of the string
object.
• The charAt() method requires one argument, which
is the index of the character that you want to copy.
• The following statement illustrates how to use the
charAt() method:
• var SingleCharacter=NameOfStringObject.charAt(index)

Retreiving a character from given position: Example


<!DOCTYPE html>
<html>
<head>
<title>Copy one character of a string</title>
</head>
<body>
<script language="Javascript" type="text/javascript">
<!--
var FirstName = 'Bob'
var Character = FirstName.charAt(0)
alert(Character)
-->
</script>
</body>
</html>

Retrieving a position(index) of character in a string


• Sometimes you won’t know the index of the
character you need because the string is supplied
to your JavaScript when the script runs.
• This occurs, for example, when the person who
runs your JavaScript enters the string.
• You can determine the index of a character by
calling the indexOf() method of the string object.
• The indexOf() method returns the index of the
character passed to it as an argument.
• If the character is not in the string, the method
returns –1.
• e.g.
• var IndexValue = string.indexOf('character')

Retrieving a position(index) of character in aq string:


Example
<!DOCTYPE html>
<html>
<head>
<title>Identifying the index of a character in a
string</title>
</head>
<body>
<script language="Javascript" type="text/javascript">
<!--
var FirstName = 'Bob'
var IndexValue = FirstName.indexOf('o')
alert(IndexValue)
if(IndexValue != -1)
{
var Character = FirstName.charAt(IndexValue)
alert(Character)
}
-->
</script>
</body>
</html>

• You can use the length value of the string object to


calculate the position of the character.
• e.g.
• var LengthOfString = string.length
• We can use the length value to calculate the index
of the character that we want to use. Here how
this is done:
• var SSNumber = '123-45-6789'
• var IndexOfCharacter = SSNumber.length - 4

Dividing Text
• Imagine a string of concatenated data elements
with only a comma separating each of them; your
mission is to copy each data element into its own
string.
• Here, each person’s name is a data
ele_x0002_ment, and your job is to copy each
name to its own string:
• var DataString = 'Bob Smith, Mary Jones, Tom
Roberts, Sue Baker'
• JavaScript developers call this a comma-delimited
string because a comma signifies the beginning and
end of each data element.
• Traditionally, data elements are transferred
between applications in a comma-delimited format.
• The application receiving the string then uses the
commas as a guide for separating the string into
data elements.
• Your task is challenging, but it can easily be
accomplished by using the split() method of the
string object.
• The split() method creates a new array and then
copies portions of the string, called a substring,
into its array elements.
• You must tell the split() method what string
(delimiter) is used to separate substrings in the
string.
• You do this by passing the string as an argument to
the split() method.
• In this example, the comma is the string that
separates substrings. Here’s how you use the split()
method:
• var NewStringArray = StringName.split('delimiter
string')
• Example
<!DOCTYPE html>
<html>
<head>
<title>Dividing a delimited string into a
substring</title>
</head>
<body>
<script language="Javascript" type="text/javascript">
<!--
var DataString = 'Bob Smith,Mary Jones,Tom
Roberts,Sue Baker'
var NewArray = DataString.split(',')
document.write(DataString);
document.write('<br>')
for (i=0; i<4; i++)
{
document.write(NewArray[i])
document.write('<br>')
}
-->
</script>
</body>
</html>

Copying a Substring
• You if you need to copy one substring, you’ll need
to use one of two other methods: substring() and
substr().
• Here’s the string that the sales representative
entered that contains the e-mail address:
• EmailAddress = '[email protected] '
• There is a good chance that the www.xyz.com is
the corporate web site for this client.
• Your job is to copy the substring 'xyz.com' from the
e-mail address and then concatenate the substring
with 'www.' to form the new string 'www.xyz.com'.
• substring() is a method of a string object that
copies a substring from a string based on a
beginning and an end position that is passed as an
argument to the substring() method.

Copying a Substring:substring() method


• The starting position specifies the first character
that is returned by the substring() method—that is,
the first character in the substring.
• The end position specifies the character that
follows the last character that is returned by the
substring() method—that is, the position of the
character that comes after the last character that
you want to include in the substring.
• Here’s how to write the substring() method:
• var NewSubstring=StringName.substring
(StartingPosition, EndPosition)
• Example
<!DOCTYPE html>
<html>
<head>
<title>Using substring()</title>
</head>
<body>
<script language="Javascript" type="text/javascript">
<!--
var EmailAddress='[email protected] '
var NewSubstring=EmailAddress.substring(7,14)
var GuessWebSite='www.'+NewSubstring
var WebSite=prompt('Enter the client web site.',
GuessWebSite )
-->
</script>
</body>
</html>

Copying a Substring:substr() method


• In the real world, you probably won’t know the
starting position and end position of characters for
your substring, because a user can enter any length
string into your application.
• You can overcome this problem by using the
substr() method along
• with other string object methods.
• You must tell it the starting position of the first
character that you want to include in the substring
and how many characters you want copied into
the substring from the starting position.
• Both positions are passed as arguments to the
substr() method.
• Here’s how you write the substr() method:
• Var NewSubstring=StringName.substr(StartingPosition,
NumberOfCharactersToCopy)

• Again, we’ll take a look at the e-mail address to


understand how the substr() method works:
• EmailAddress = '[email protected] '
• The starting position is 7 since the first character of
the substring is x (the eighth character in the string,
zero-based index).
• We want the substr() method to copy seven
characters into the substring beginning with
character number 7.
• This results in the substring 'xyz.com'.
• Example
<!DOCTYPE html>
<html>
<head>
<title>Using substr()</title>
</head>
<body>
<script language="Javascript" type="text/javascript">
<!—
var EmailAddress=prompt('Enter your clients email
address.', ' ')
var StartPosition=EmailAddress.indexOf('@')+1
var NumCharactersToCopy=EmailAddress.length -
StartPosition
var NewSubstring=EmailAddress.substr(StartPosition,
NumCharactersToCopy)
var GuessWebSite='www.'+NewSubstring
var WebSite=prompt('Enter the client web site.',
GuessWebSite )
-->
</script>
</body>
</html>

Converting Numbers and Strings


• A number and a string are two different types of
data in JavaScript.
• A number is a value that can be used in a
calculation; a string is text and can include
numbers, but those numbers cannot be used in
calculations.
• If you need to convert string values to number
values, you can do so by convert_x0002_ing a
number within a string into a numeric value that
can be used in a calculation.
• You do this by using the parseInt() method and
parseFloat() method of the string object.

Converting Numbers and Strings:parseInt()


• The parseInt() method converts a number in a
string to an integer numeric value, which is a whole
number.
• You write the parseInt() method this way:
• var num=parseInt(StringName)
• Here’s an example. Suppose you have the following
string:
• var StrCount = '100'
• You cannot use this number in a calculation
because '100' is a string and not a numeric value—
that is, the browser treats this as text and not a
number.
• You must convert this string to a numeric value
before you can use the 100 in a calculation.
• The following statement is used for this conversion:
• var StrCount = '100'
• var NumCount = parseInt(StrCount)

Converting Numbers and Strings:parseFloat()


• The parseFloat() method is used similarly to the
parseInt() method,
• except the parseFloat() method is used with any
number that has a decimal value.
• (Think of a decimal number whenever you see the
word float.)
• Here’s how to use the parseFloat() method:
• var StrPrice='10.95'
• var NumPrice=parseFloat(StrCount)

Numbers to Strings: toString() method


• You need to convert a numeric value to a string
before the number can be used in the string.
• You do this by calling the toString() method of the
number object.
• The toString() method can be used to convert both
integers and decimal values (floats).
• Here’s how to convert a number value to a string:
Var NumCount = 100
var StrCount = NumCount.toString()
• Alternatively, you can use the concatenation
operator (+) to combine a string and a number.
• The concatenation operator automatically calls the
toString() method on numeric values to convert
them to a string.
var x = 500
var y = 'abc'
var z = x + y
Variable z now has the value '500abc' and has been
converted to a string.
Changing the Case of the String:
toUpperCase() method and toLowerCase() method
• You may need to indicate a string in all uppercase
or all lowercase letters.
• JavaScript developers avoid issues related to case
by changing the case of both strings to ether
uppercase or lowercase before comparing them.
• This is done by using the toUpperCase() method
and toLowerCase() method of the string object.
• The functions return a new string that’s either all
uppercase or all lowercase.
• The original string is unchanged.
• The following code segment shows how this is
done using the toUpperCase() method, which
converts a string to uppercase characters:
var Comp1 = 'FedEx'
var Comp2 = 'Fedex'
if (Comp1.toUpperCase() == Comp2.toLowerCase())
• The following code segment uses the toLowerCase()
method to convert a
• string to lowercase characters:
var Comp1 = 'FedEx'
var Comp2 = 'Fedex'
if (Comp1.toLowerCase() == Comp2.toLowerCase())

Strings and Unicode:charCodeAt() method and


fromCharCode() method
• You probably already know that a computer
understands only numbers and not characters.
• You might not know that when you enter a
character, such as the letter w, the character is
automatically converted to a number called a
Unicode number that your computer can
understand.
• Unicode is a standard that assigns a number to
every character, number, and symbol that can be
displayed on a computer screen, including
characters and symbols that are used in all
languages.
• You can determine the Unicode number or the
character that is associated with a Unicode number
by using the charCodeAt() method and
fromCharCode() method.
• Both are string object methods.
• The charCodeAt() method takes an integer as an
argument that represents the index of the
character in which you’re interested.
• If you don’t pass an argument, it defaults to index 0.
• The charCodeAt() method returns the Unicode
number of the string:
var UnicodeNum = StringName.charCodeAt()
Here’s how to determine the Unicode number of
the
letter w:
var Letter = 'w'
var UnicodeNum = Letter.charCodeAt()
• The Letter.charCodeAt() method returns the
number 119, which is the Unicode number that is
assigned the letter w.
• Uppercase and lowercase versions of each letter
have a unique Unicode number.
• If you need to know the character, number, or
symbol that is assigned to a Uni_x0002_code
number, use the fromCharCode() method.
• The fromCharCode() method requires one
argument, which is the Unicode number.
• Here’s how to use the fromCharCode() method to
return the letter w.
var Letter = String.fromCharCode(119)

Replace() Method of String


The replace() method returns a new string with one,
some, or all matches of a pattern replaced by
a replacement. The pattern can be a string or a RegExp,
and the replacement can be a string or a function called
for each match.
If pattern is a string, only the first occurrence will be
replaced. The original string is left unchanged.
Example 1:
var str = 'The quick brown fox jumps over the lazy dog.
If the dog reacted, was it really lazy?';

var str2=str.replace('dog', 'monkey'));

expected output: "The quick brown fox jumps over the


lazy monkey. If the dog reacted, was it really lazy?"
Example 2:

regex = /Dog/i;
var str2=str.replace(regex, 'ferret')
expected output: "The quick brown fox jumps over the
lazy ferret. If the dog reacted, was it really lazy?"

You might also like