You are on page 1of 77

Client Side Scripting Languages Question Banks

MSBTE CAMPUS
msbtebook.blogspot.com
BY :-- Vishal Chavare

Co marks Question

1 2 what are arithmetic and logical operator used in java script

1 4 write a script that reads an integer and displays whether it is a prime number or not

1 4 Explain the use of continue statement with the help of example

1 2 Explain the feature of javascript

1 2 what is conditional operator in javascript

1 4 Explain the terms-propery,method,dot syntax

1 4 Explain six types of values in javascript

1 4 Write a javascript to display welcome message in javascript

1 6 Develop a javascript to generate armstrong numbers between the range 1 to 100

1 2 State the use of dot syntax in JavaScript with the help of suitable example.

1 2 List and explain Logical operators in JavaScript.

1 2 Write a JavaScript that identifies a running browser.


Write syntax of and explain prompt method in JavaScript with the help of suitable
1 4 example.

1 4 Write a JavaScript that displays all properties of window object. Explain the code .

1 4 Write a JavaScript function that checks whether a passed string is palindrome or not.

Prepared By –Vishal Chavare


Client Side Scripting Languages Question Banks

1 2 State use of getters and setters

1 2 Write a JavaScript that displays first 20 even numbers on the document window.

1 4 Write a program to print sum of even numbers between 1 to 100 using for loop.
Write a JavaScript program which compute, the average marks of the following students
Then, this average is used to determine the corresponding grade.

Student Marks
Name

Advait 80

Anay 77

Manyata 88

Saanvi 95

Saachi 68

The grades are computed as follows :

Range Grade

<60 F

<70 D

<80 C

<90 B
<100 A
1 4

2 2 how will you define function?

2 2 what is string?

2 4 write a javascript to call a function with argument for addition of two numbers

2 4 write a javascript to convert a string to number

2 2 Define array

Prepared By –Vishal Chavare


Client Side Scripting Languages Question Banks

2 4 Explain the use of push and pop functions

2 4 what is difference between group of checkbox buttons and group of radio button

2 6 write a short note -object as associative array in javascript

2 2 State and explain any two properties of array object

2 4 Write a JavaScript function to insert a string within a string at a particular position

2 4 Write a JavaScript function to count the number of vowels in a given string.

2 4 Write a JavaScript that find and displays number of duplicate values in an array.

2 4 Develop JavaScript to convert the given character to Unicode and vice versa.

2 4 Differentiate between concat() and join() methods of array object.

3 4 Generate college Admission form using html form tag

3 4 State the use of following methods. charCodeAt() fromCharCode()


Give syntax of and explain the use of “with” statement/clause in JavaScript using suitable
3 2 example.
Write HTML Script that displays textboxes for accepting Name, middlename, Surname of
the user and a Submit button. Write proper JavaScript such that when the user clicks on
submit button all texboxes must get disabled and change the color to “RED”. and with
respective labels.Constructs the mailID as <name>.<surname>@msbte.com and displays
mail ID as message. (Ex. If user enters Rajni as name and Pathak as surname mailID will
3 6 be constructed as rajni.pathak@msbte.com) .
Write HTML Script that displays dropdownlist containing options NewDelhi, Mumbai,
Bangalore. Write proper JavaScript such that when the user selects any options
corresponding description of about 20 words and image of the city appear in table which
3 6 appears below on the same page.

3 2 what is event?

3 2 what is the used of text component?

3 4 explain -form objects and elements

Prepared By –Vishal Chavare


Client Side Scripting Languages Question Banks

3 4 write a javascipt to illustrate keyboard event.

3 2 Explain the uses of forms

3 4 how to create password field in html form?

3 4 Explain the scope of variable with the help of programming example


write a javascript to create three categories -fruit ,flower,and color .based on the the
3 6 selection of category ,the items in the option list must get changed

4 2 Enlist and explain the use of any two Intrinsic JavaScript functions.
Write the syntax of and explain use of following methods of JavaScript Timing Event.
4 4 setTimeout() setInterval()

4 2 State and explain what is a session cookie ?


Write a function that prompts the user for a color and uses what they select to set the
4 4 background color of the new webpage opened .

4 2 what are the attribute s are used to set position of window

4 2 give syntax for opening a windoe

4 2 what is the method of setting expiry date of cookies?

4 4 Write javascript to open a new window

4 2 what is cookies?

4 4 Explain how to create cookies in javascript?

4 4 Explain the syntax for opening window?

4 6 what is the use of setTimeout () function ?write a javascript to illustrate it


State what is a regular expression? Explain its meaning with the help of a suitable
5 4 example.

5 2 what is frame ?

Prepared By –Vishal Chavare


Client Side Scripting Languages Question Banks

5 2 whta is rollover?

5 4 how will you make the rollover more effiecient?

5 4 Explain how to set the frame bordersinvisible

5 2 Define term regular expression

5 4 Explain any four commonly used methods in regular expression

5 4 What are the methods used most commonly during the rollover?

5 4 Explain frame set tag along with the arrtibutes used in it


write a java script in which when user rollover the name of fruit,the corresponding image
should be display .along with the appropriatote image display ,additional window should
5 6 pop up display ing the benefit of each fruit.
Write a webpage that accepts Username and adharcard as input texts. When the user
enters adhaarcard number ,the JavaScript validates card number and diplays whether card
number is valid or not. (Assume valid adhaar card format to be nnnn.nnnn.nnnn or
5 4 nnnn-nnnn-nnnn).
Write a webpage that diplays a form that contains an input for Username and password.
User is prompted to enter the input and password and password becomes value of the
cookie. Write The JavaScript function for storing the cookie . It gets executed when the
5 6 password changes.
Construct regular expression for validating the phone number in following format only
5 2 :(nnn)-nnnn-nnnn OR nnn.nnnn.nnnn
Write a JavaScript that creates a persistent cookies of Itemnames. Write appropriate
5 4 HTML script for the same.

5 4 Write a JavaScript function to check whether a given value is valid IP value or not
Write a script for creating following frame structure :

FRAME1

FRAME2 FRAME3

 FRUITS

 FLOWERS

 CITIES
5 6

Prepared By –Vishal Chavare


Client Side Scripting Languages Question Banks

Fruits, Flowers and Cities are links to the webpage fruits.html, flowers.html, cities.html
respectively. When these links are clicked corresponding data appears in “FRAME3”.

Design the frameset tag for following frame layout :


FRAME1

FRAME2

FRAME3

5 2

6 4 List ways of Protecting your webpage and describe any one of them.

6 6 Develop a JavaScript Program to Create Rotating Banner Ads with URL Links.
Create a slideshow with the group of four images, also simulate the next and previous
6 6 transition between slides in your JavaScript.

6 2 State the method to put message in web browser status bar?

6 4 Write a JavaScript program to create rollover effect for three images.

6 4 Write a JavaScript program that create a scrolling text on the status line of a window.

6 2 what is banner ad?

6 2 what is dynamic menu?

6 4 write a javascript to create a simple pulldown menu

6 4 Explain – sliding menu and scrollable menu

6 2 what is the use of status bar in web application

6 4 write a javascript to create and display banner.


write a program that disable the right click button and displays the message right click
6 6 button is disabled

Prepared By –Vishal Chavare


Client Side Scripting Languages Question Banks

MSBTE CAMPUS
msbtebook.blogspot.com
BY :-- Vishal Chavare

Prepared By –Vishal Chavare


Scheme – I
Question Paper model answers
Program Name : Diploma in Engineeering Group
Program Code : CO / CM / CW / IF
Semester : Fifth
Course Title : Client Side Scripting Language (Elective)
Marks : 70 Time: 3 Hrs.
Instructions:
(1) All questions are compulsory.
(2) Illustrate your answers with neat sketches wherever necessary.
(3) Figures to the right indicate full marks.
(4) Assume suitable data if necessary.
(5) Preferably, write the answers in sequential order.

Q.1) Attempt any FIVE of the following. 10 Marks


a) State the use of dot syntax in JavaScript with the help of suitable example.
Answer: Dot syntax is the simplest form of accessing an object's property or
method in JavaScript. It is a shorthand for referencing object properties or
methods.
Example:
// Accessing a property of an object
let user = {
name: 'John',
age: 28
};

Aditi Gharat
console.log(user.name); // Output: John
// Calling a method of an object
let user = {
name: 'John',
age: 28,
sayHi() {
console.log(`Hi, my name is ${this.name}`);
}
};
user.sayHi(); // Output: Hi, my name is John

b) List and explain Logical operators in JavaScript.


Answer:
A logical operator is an operator that is used to perform logical operations on two
boolean expressions. The following are the logical operators in JavaScript:

1. && (AND): The && operator is used to evaluate if both expressions are true.
The expression will only return true if both expressions are true.

2. || (OR): The || operator is used to evaluate if either expression is true. The


expression will return true if either expression is true.

3. ! (NOT): The ! operator is used to evaluate if an expression is false. The


expression will return true if the expression is false.

Aditi Gharat
c) Write a JavaScript that identifies a running browser.
Answer:
<html>
<body>
<script >
// Get the user agent string
var userAgentString = navigator.userAgent;

// Detect Chrome
if (userAgentString.indexOf("Chrome") > -1) {
alert("You are using Chrome!");
}

// Detect Firefox
else if (userAgentString.indexOf("Firefox") > -1) {
alert("You are using Firefox!");
}

// Detect Safari
else if (userAgentString.indexOf("Safari") > -1) {
alert("You are using Safari!");
}

// Detect Internet Explorer


else if (userAgentString.indexOf("MSIE") > -1) {
alert("You are using Internet Explorer!");
}

// Detect Edge
else if (userAgentString.indexOf("Edge") > -1) {
alert("You are using Edge!");
}

// Detect Opera

Aditi Gharat
else if (userAgentString.indexOf("Opera") > -1) {
alert("You are using Opera!");
}

// Unknown
else {
alert("We could not detect which browser you are using!");
}

</script>
</body>
</html>

d) Write a JavaScript that initializes an array called “Fruits” with names of five
fruits. The script then displays the array in a message box.
Answer:
<html>
<head>
<script type="text/javascript">
var Fruits = ["Apple", "Banana", "Orange", "Kiwi", "Strawberry"];
alert("Fruits: " + Fruits);
</script>
</head>
</html>

Aditi Gharat
e) Give syntax of and explain the use of “with” statement/clause in JavaScript
using suitable example.
Answer:
Syntax:

with (object) {
// code
}

The 'with' statement is used to provide a shorthand to access methods and


properties of an object. It avoids the use of the object's name in the code, which
can make the code more readable and maintainable.

Example:

var person = {
name: "John Doe",
age: 25
};

with (person) {
console.log(name + " is " + age + " years old.");
}

// Output: "John Doe is 25 years old."

f) Enlist and explain the use of any two Intrinsic JavaScript functions.
Answer:
Intrinsic functions are built-in functions that are part of the JavaScript language,
and are available to all JavaScript programs. They are used to perform common
tasks such as string manipulation, mathematical calculations, and other
operations.

Aditi Gharat
1) parseInt() :- The parseInt() function is used to convert a string into an integer
value. It takes a string as an argument and returns an integer if the string is valid,
otherwise it returns NaN (not a number). This function is useful when working
with numbers that are stored as strings in variables.

2) Math.round() :- The Math.round() function is used to round a number to the


nearest integer. It takes a number as an argument and returns the rounded
number. This function is useful for rounding numbers to the nearest whole
number or decimal place.

g) State and explain what is a session cookie ?


Answer:
A session cookie is a type of cookie that is stored in a user's browser for a single
session or visit. It is used to store information about the user's interactions and
activity during the session. Session cookies are deleted when the browser is
closed or the user logs out.
Session cookies are typically used to:
1. Store session-specific information such as a shopping cart, login credentials, or
user preferences.
2. Track user activity on a website, such as pages visited or time spent on a page.
3. Remember user choices, such as language or font size preferences.
4. Provide security features, such as allowing users to remain logged in for a
certain amount of time.
5. Provide a better user experience, such as by auto-filling form fields.

Aditi Gharat
Q.2) Attempt any THREE of the following. 12 Marks
a) Write syntax of and explain prompt method in JavaScript with the help of
suitable example.
Answer:
Syntax:
window.prompt( message, default);
Example:
<html>
<head>
<script type="text/javascript">
function promptUser(){
var userName = window.prompt("Please enter your name", "Harry
Potter");
document.write("Welcome " + userName);
}
</script>
</head>
<body>
<input type="button" onclick="promptUser()" value="Prompt Box" />
</body>
</html>
Explanation:
The prompt() method in JavaScript displays a dialog box that prompts the user for
input. It takes two parameters; the message to be displayed, and a default value.
In the above example, when the user clicks on the “Prompt Box” button, the
window.prompt method is called which displays a dialog box asking the user to

Aditi Gharat
enter their name. The message displayed is "Please enter your name" and the
default value is "Harry Potter". The user can enter any value, which is then stored
in the userName variable.

b) Write a JavaScript program which compute, the average marks of the


following students Then, this average is used to determine the corresponding
grade.
Student Marks
Name
Advait 80
Anay 77
Manyata 88
Saanvi 95
Saachi 68
The grades are computed as follows :
Range Grade
<60 F
<70 D
<80 C
<90 B
<100 A

Answer:
<html>
<body>
<script>
var student = ["Advait", "Anay", "Manyata", "Saanvi", "Saachi"];

var marks = [80, 77, 88, 95, 68];

Aditi Gharat
var total = 0;
for(var i=0; i < marks.length; i++) {
total += marks[i];
}

var avg = total/marks.length;

document.write("Average marks = " + avg + "<br>");

if ( avg < 60) {


document.write("Grade: F");
}
else if (avg < 70) {
document.write("Grade: D");
}
else if (avg < 80) {
document.write("Grade: C");
}
else if (avg < 90) {
document.write("Grade: B");
}
else {
document.write("Grade: A");
}
</script>
</body>
</html>

Aditi Gharat
c) Write a JavaScript that displays all properties of window object. Explain the
code.
Answer:

<html>
<head>
<script type="text/javascript">
var prop;
for (prop in window) {
document.write(prop + " : " + window[prop] + "<br>");
}
</script>
</head>
<body>
</body>
</html>

Explanation: This JavaScript code will loop through all the properties of the
window object and display them on the page. It starts by declaring the variable
prop. Then, it loops through all the properties of the window object. For each
property, it will write the property name and the value of the property on the
page.

d) Write a JavaScript function that checks whether a passed string is palindrome


or not.
Answer:
<html>

<body>

<script>
function isPalindrome(str) {

Aditi Gharat
var reverseString = str.split('').reverse().join('');
if (reverseString === str) {
return true;
} else {
return false;
}
}
var inputString = prompt("Please enter a string to check if it is palindrome or
not");
if (isPalindrome(inputString)) {
alert("The entered string is a palindrome!");
} else {
alert("The entered string is not a palindrome!");
}
</script>

</body>

</html>

Q.3) Attempt any THREE of the following. 12 Marks


a) Differentiate between concat() and join() methods of array object.
Answer:
concat() join()
1. The concat() method is used to 1.The join() method is used to join
join two or more arrays into one all the elements of an array into a
array. string.
2. It does not change the existing 2. It does not change the existing
array, it returns a new array. array, it returns a new string.
3. Both methods are used to 3. Both methods are used to
combine elements of an array, but combine elements of an array,
the concat() method creates a while the join() method creates a
new array string.

Aditi Gharat
4. The concat() method does not 4. The join() method takes an
take any argument and returns a optional argument which is the
new array with the elements of the separator between the elements
original array combined. of the array.
5.Eg: 5.Eg:
var str = cars.concat() var str = cars.join(' ')
The value of str is 'BMW, Audi, The value of str in this case is 'BMW
Maruti' Audi Maruti'
b) Write a JavaScript function to count the number of vowels in a given string.
Answer:
<html>
<head>
<title>Vowel Counter</title>
<script>
function vowel_count(str) {
let count = 0;
const vowels = ["a", "e", "i", "o", "u"];

for (let i = 0; i < str.length; i++) {


if (vowels.includes(str[i].toLowerCase())) {
count++;
}
}
return count;
}
</script>
</head>
<body>
<h2>Vowel Counter</h2>
<p>Enter a string to see how many vowels it contains:</p>
<input type="text" name="string" id="string">
<button
onclick="alert(vowel_count(document.getElementById('string').value))">Count
Vowels</button>

Aditi Gharat
</body>
</html>

c) Write a JavaScript that find and displays number of duplicate values in an


array.
Answer:
<html>
<head>
<title>Find Duplicates</title>
</head>
<body>
<script type="text/javascript">
function findDuplicates(arr) {
let duplicates = {};
arr.forEach(function(item) {
if (duplicates.hasOwnProperty(item)) {
duplicates[item]++;
} else {
duplicates[item] = 1;
}
});
return duplicates;
}
let arr = [1, 2, 3, 2, 4, 5, 6, 2, 7, 8, 9, 2];
let result = findDuplicates(arr);
document.write("Number of Duplicates = " + result[2]);
</script>
</body>
</html>

Aditi Gharat
d) Write a function that prompts the user for a color and uses what they select
to set the background color of the new webpage opened .
Answer:
<html>
<head>
<title>Change Background Color</title>
<script type="text/javascript">
function setBackground() {
var color = prompt("Please enter a background color","");
if (color != null) {
document.body.style.background = color;
}
}
</script>
</head>

<body>
<button onclick="setBackground()">Change Background Color</button>
</body>
</html>

Aditi Gharat
Q.4) Attempt any THREE of the following. 12 Marks
a) State what is a regular expression? Explain its meaning with the help of a
suitable example.
Answer:
A regular expression is a sequence of characters that define a search pattern. It is
mainly used for string pattern matching. Regular expressions are very powerful
and can be used to perform a wide variety of string manipulations.

For example, the following HTML code counts the number of words in a given
sentence:

<html>
<head>
<script>
function wordCount() {
// Get sentence from text area
let sentence = document.getElementById("input").value;

// Create a regular expression to match any word


let regex = /\w+/g;

// Get all the words in the sentence


let words = sentence.match(regex);

// Show the word count


alert(words.length);
}
</script>
</head>
<body>
<textarea id="input" rows="4" cols="50"></textarea>
<br>
<button onclick="wordCount()">Word Count</button>

Aditi Gharat
</body>
</html>

In the above example, the regex /\w+/g is used to create a search pattern that
looks for any word in the given sentence. The words are then counted and
displayed as an alert.

b) Write a webpage that accepts Username and adharcard as input texts. When
the user enters adhaarcard number ,the JavaScript validates card number and
diplays whether card number is valid or not. (Assume valid adhaar card format
to be nnnn.nnnn.nnnn or nnnn-nnnn-nnnn).
Answer:
<!DOCTYPE html>
<html>
<head>
<title>Adhaar Card Validation</title>
<script>
function validateForm() {
var adhaarCard = document.forms["myForm"]["adhaarCard"].value;
if (adhaarCard.length != 14) {
alert("Adhaar Card Number Length should be 14");
return false;
}
var regex = /^\d{4}\-\d{4}\-\d{4}$/;
if (regex.test(adhaarCard) == false) {
alert("Adhaar Card Number should be in format nnnn.nnnn.nnnn or
nnnn-nnnn-nnnn");
return false;
}
}
</script>
</head>
<body>

Aditi Gharat
<form name="myForm" action="" onsubmit="return validateForm()"
method="post">
<div>
<label>Username: </label>
<input type="text" name="username">
</div>
<div>
<label>Adhaar Card Number: </label>
<input type="text" name="adhaarCard">
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>

c) Write the syntax of and explain use of following methods of JavaScript Timing
Event.
a. setTimeout()
b. setInterval()
Answer:
a. setTimeout():
The setTimeout() method calls a function or evaluates an expression after a
specified number of milliseconds.
Syntax:
setTimeout(function, milliseconds, param1, param2, ...)
Example:
setTimeout(function(){ alert("Hello") }, 3000);

Aditi Gharat
b. setInterval():
The setInterval() method calls a function or evaluates an expression at specified
intervals (in milliseconds).
Syntax:
setInterval(function, milliseconds, param1, param2, ...)
Example:
setInterval(function(){ alert("Hello") }, 3000);

d) Develop JavaScript to convert the given character to Unicode and vice versa.
Answer:
<html>
<head>
<script type="text/javascript">
function charToUnicode()
{
var text = document.getElementById("text").value;
var result="";
for(var i=0; i<text.length; i++)
{
result += "\\u" + text.charCodeAt(i).toString(16);
}
document.getElementById("result").value=result;
}

function unicodeToChar()
{
var code = document.getElementById("code").value;
var result = "";
for(var i=0; i<code.length; i+=4)
{
result += String.fromCharCode(parseInt(code.substr(i, 4), 16));

Aditi Gharat
}
document.getElementById("result2").value=result;
}
</script>
</head>
<body>
<h1>Character to Unicode Converter</h1>
<input type="text" id="text" />
<input type="button" value="Convert" onclick="charToUnicode()" />
<input type="text" id="result" />
<h1>Unicode to Character Converter</h1>
<input type="text" id="code" />
<input type="button" value="Convert" onclick="unicodeToChar()" />
<input type="text" id="result2" />
</body>
</html>

e) List ways of Protecting your webpage and describe any one of them.
Answer:
Ways to Protect a Webpage:
1. Use Secure Passwords: Utilizing strong and secure passwords is one of the most
effective ways to protect a webpage. Passwords should be complex and contain a
combination of upper and lowercase letters, numbers, and special characters.
2. Implement Two-Factor Authentication: Two-factor authentication (2FA) is a
security protocol that requires users to provide two pieces of authentication
information to access a particular resource. This can include a combination of a
username and password, as well as something unique to the user, such as a one-
time PIN.
3. Utilize SSL Encryption: SSL (Secure Socket Layer) is an encryption protocol that
provides secure communication between two devices or networks. It encrypts

Aditi Gharat
data that is sent over the network, so even if it is intercepted, the data cannot be
read.
4. Use Firewalls: A firewall is a system that prevents unauthorized access to or
from a private network. It monitors incoming and outgoing network traffic and
blocks suspicious activity or malicious traffic.
5. Monitor Access Logs: Access logs are a record of all the times someone has
accessed a webpage. By monitoring access logs, administrators can quickly spot
any suspicious activity and take appropriate action.

Example:
Using Secure Passwords: Secure passwords are an important part of protecting a
webpage. Passwords should be complex and contain a combination of upper and
lowercase letters, numbers, and special characters. It is important to not use the
same password for multiple accounts and to change passwords periodically.
Additionally, it is recommended to use a password manager to store passwords
securely and make them easier to remember.

Aditi Gharat
Q.5) Attempt any TWO of the following. 12 Marks
a) Write HTML Script that displays textboxes for accepting Name, middlename,
Surname of the user and a Submit button. Write proper JavaScript such that
when the user clicks on submit button
i) all texboxes must get disabled and change the color to “RED”. and with
respective labels.
ii) Constructs the mailID as <name>.<surname>@msbte.com and displays mailID
as message. (Ex. If user enters Rajni as name and Pathak as surname mailID will
be constructed as rajni.pathak@msbte.com) .
Answer:
<html>
<head>
<script>
function Submit(){
document.getElementById("name").disabled = "true";
document.getElementById("middlename").disabled = "true";
document.getElementById("surname").disabled = "true";
document.getElementById("name").style.backgroundColor="red";
document.getElementById("middlename").style.backgroundColor="red";
document.getElementById("surname").style.backgroundColor="red";

var name = document.getElementById("name").value;


var middlename = document.getElementById("middlename").value;
var surname = document.getElementById("surname").value;

var mailID = name+ surname + "@msbte.com";

alert("MailID : " + mailID);


}
</script>
</head>
<body>

Aditi Gharat
<form>
<label>Name</label><input type="text" id="name">
<br>
<label>Middle Name</label><input type="text" id="middlename">
<br>
<label>Surname</label><input type="text" id="surname">
<br>
<input type="button" value="Submit" onclick="Submit()">
</form>
</body>
</html>

b) Write a webpage that diplays a form that contains an input for Username and
password. User is prompted to enter the input and password and password
becomes value of the cookie. Write The JavaScript function for storing the
cookie . It gets executed when the password changes.
Answer:
<html>
<head>
<title>Form for Username and Password</title>
</head>
<body>
<form>
Username: <input type="text" name="username" id="username" />
<br />
Password: <input type="password" name="password" id="password" />
<br />
<input type="submit" value="Submit" />
</form>

<script type="text/javascript">
function storeCookie(){
var username = document.getElementById("username").value;

Aditi Gharat
var password = document.getElementById("password").value;
var expDate = new Date();
expDate.setTime(expDate.getTime() + (1 * 24 * 60 * 60 * 1000));
var expires = "expires="+ expDate.toUTCString();
document.cookie = "username=" + username + "; " + expires;
document.cookie = "password=" + password + "; " + expires;
}

document.getElementById("password").onchange = storeCookie;
</script>

</body>
</html>

c) Write a script for creating following frame structure :


FRAME1

FRAME2 FRAME3

 FRUITS
 FLOWERS
 CITIES

Fruits, Flowers and Cities are links to the webpage fruits.html, flowers.html,
cities.html respectively. When these links are clicked corresponding data
appears in “FRAME3”.
Answer:
<html>
<head>
<title>Frame Demo</title>
</head>
<body>
<table border="1">

Aditi Gharat
<tr>
<td align="center" colspan="2">
FRAME 1
</td>
</tr>
<tr>
<td>
FRAME 2
<ul>
<li>
<a href="fruits.html" target="mainframe">FRUITS</a>
</li>
<li>
<a href="flowers.html" target="mainframe">FLOWERS</a>
</li>
<li>
<a href="cities.html" target="mainframe">CITIES</a>
</li>
</ul>
</td>
<td>
FRAME 3<BR>
<iframe name="mainframe"></iframe>
</td>
</tr>
</table>
</body>
</html>

Aditi Gharat
Q.6) Attempt any TWO of the following. 12 Marks

a) Write HTML Script that displays dropdownlist containing options NewDelhi,


Mumbai, Bangalore. Write proper JavaScript such that when the user selects
any options corresponding description of about 20 words and image of the city
appear in table which appears below on the same page.
Answer:
<!DOCTYPE html>
<html>
<head>
<script>
function showDescription(cityName) {
if (cityName == "NewDelhi") {
document.getElementById("cityDescription").innerHTML = 'New Delhi is the
capital of India and is the second most populous city in India. It is one of the
oldest cities in the world and is home to a number of landmarks including the
Rashtrapati Bhavan, Parliament House, India Gate and more.';
document.getElementById("cityImage").src = "newDelhi.jpg";
} else if (cityName == "Mumbai") {
document.getElementById("cityDescription").innerHTML = 'Mumbai is the most
populous city in India and is the financial and entertainment capital of the
country. It is home to some of India’s most iconic landmarks such as the Gateway
of India, Marine Drive, Haji Ali Dargah, and more.';
document.getElementById("cityImage").src = "mumbai.jpg";
}
else if (cityName == "Bangalore") {
document.getElementById("cityDescription").innerHTML = 'Bangalore is the
capital of the Indian state of Karnataka. It is known as the "Garden City of India"
due to its many gardens and parks. Bangalore is also home to a number of IT
companies and is referred to as the "Silicon Valley of India".';
document.getElementById("cityImage").src = "bangalore.jpg";
}
}
</script>

Aditi Gharat
</head>
<body>

<h1>Select a City</h1>

<select onchange="showDescription(this.value)">
<option value="NewDelhi">New Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Bangalore">Bangalore</option>
</select>

<br><br>

<table>
<tr>
<td>Description:</td>
<td id="cityDescription"></td>
</tr>
<tr>
<td>Image:</td>
<td><img id="cityImage" width="200" height="200"></td>
</tr>
</table>

</body>
</html>

b) Develop a JavaScript Program to Create Rotating Banner Ads with URL Links.
Answer:
<html>
<head>
<script>

var ad_images = new Array("banner1.jpg", "banner2.jpg", "banner3.jpg");

Aditi Gharat
var thisAd = 0;

function rotate(){
if(thisAd == ad_images.length-1){
thisAd = 0;
}else {
thisAd++;
}
document.getElementById("adBanner").src=ad_images[thisAd];
}

window.setInterval(rotate, 3000);

</script>
</head>
<body>

<h3>Rotating Banner Ads with URL Links</h3>

<a href="http://www.example1.com" target="_blank">


<img id="adBanner" src="banner1.jpg" width="400px" height="200px" />
</a>

</body>
</html>

Aditi Gharat
c) Create a slideshow with the group of four images, also simulate the next and
previous transition between slides in your JavaScript.
Answer:
<html>
<head>
<script>
pics = new Array('1.jpg' , '2.jpg' , '3.jpg', '4.jpg');
count = 0;
function slideshow(status)
{
if (document.images)
{
count = count + status;
if (count > (pics.length - 1))
{
count = 0;
}
if (count < 0)
{
count = pics.length - 1;
}
documet.imag1.src = pics[count];
}
}
</script>
</head>
<body>
<img src="1.jpg" width="200" name="img1">
<br>
<input type="button" value="Next" onclick="slideshow(1)">
<input type="button" value="Back" onclick="slideshow(-1)">
</body>
</html>

Aditi Gharat
SANDIP FOUNDATIONS
SANDIP POLYTECHNIC, NASHIK
Academic Year(2022-23)
Question for OR/PR Exam Winter 2022

1.Write a program to read arithmetic expression from user, evaluate it


and display the answer using alert box.
Ans:
<html>
<head>
<title>Arithmetic Operation </title>
<head>
<body>
<script type="text/javascript" language="javascript">
var x = 10;
var y = 4;
document.write("Addtion:"+x+y);
document.write("<br>Sub:"+x-y);
document.write("<br>mul:"+x*y);
document.write("<br>Div:"+x/y);
document.write("<br>Per:"+x%y);
</script>
</body>
</html>

2.Write a program to display even and odd numbers.


Ans:
<html>
<head>
<title> Even & Odd Number </title>
<head>
<body>
<script type = "text/javascript">
var no= prompt("Enter the number");
if(no%2==0)
{
alert("number is even");
}
else
{
alert("number is odd");
}
</script>
</body>
</html>
3.Write a program to display prime numbers
Ans:
<html>
<head>
<title>Prime Number</title>
</head>
<script type="text/javascript">
function prime() {
var n, i;
var flag = false;
n = document.forms.myform.n.value;
if (n == 0 || n == 1)
{
alert(n + " is not prime number");
}
else
{
for (i = 2; i < n; i++)
{
if (n % i == 0)
{
flag = true;
break;
}
}
if (flag == true)
{
alert(n + " is not prime");
}
else
{
alert(n + " is prime");
}
}
}
</script>
<body>
<form name="myform">
Enter the Number : <input type="text" name="n" /> <br />
<br />

<input type="button" value="Submit" onClick="prime()" />


<br />
</form>
</body>
</html>

4.Write a program to perform all the array operations.


Ans:
<html>
<head>
<title>Array Operation</title>
</head>
<body>
<script type="text/javascript">
a = new Array();
a[0] = "C";
a[1] = "C++";
a[2] = "Java";
a[3] = "VB";
document.write("<br>The Array elements are:");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
document.write("<br>Select the operations you want to perform on
array");
document.write("<br>A.Adding an array element using push() method");
document.write("<br>B.Adding an array element using pop() method");
document.write("<br>C.Adding an array element using unshift() method");
document.write("<br>D.Adding an array element in between using splice()
method");
document.write("<br>E.Adding an array element to another array using
concat() method");
document.write("<br>F.Adding an array element at perticular index");
document.write("<br>G.Sort an array ement using sort() method");
document.write("<br>H.Reverse an array element using reverse()
method");
document.write("<br>I.Shift an array element using shift() method");
document.write("<br>J.Unshift an array element using unshift() method");
document.write("<br>K.Delete an array element using delete() method");
document.write("<br>L.Adding an array element using splice() method");
document.write("<br>M.Divide an array element using slice() method");
var choice = prompt("Enter your choice");
alert("You have selected option" + choice);

switch (choice) {
case "A":
a.push("PHP");
document.write("<br>Array Element after applying push method<br>");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
break;
case "B":
a.pop();
document.write("<br>Array Element after applying pop method<br>");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
break;
case "C":
a.unshift("PHP", "Pascal");
document.write("<br>Array Element after applying unshift()
method<br>");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
break;
case "D":
a.splice(1, 0, "PHP");
document.write("<br>Array Element after applying splice()
method<br>");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
break;
case "E":
var newlist = a.concat("PHP", "Pascal");
document.write("<br>Adding an Array Element into another array
concat() method<br>");
for (i = 0; i < newlist.length; i++) {
document.write(newlist[i] + "<br>");
}
break;
case "F":
a[2] = "PHP";
document.write("<br>Add an Array Element at a Particular Index<br>");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
break;
case "G":
a.sort();
document.write("<br>Sort an Array Element after applying sort()
method<br>");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
break;
case "H":
a.reverse();
document.write("<br>Reverse an Array Element after applying reverse()
method<br>");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
break;
case "I":
var newlist = a.join(" and ");
document.write("<br>Join-This method returns the array as a string. The
elements will be separated by a specified separator. The default separator is
comma (,)<br>");
for (i = 0; i < newlist.length; i++) {
document.write(newlist[i] + "<br>");
}
break;
case "J":
a.unshift("PHP");
document.write("<br>Removes first element of an array using
Shift()<br>");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
break;
case "K":
delete a[0];
document.write("<br>Delete element of an array using delete()<br>");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
break;
case "L":
a.splice(2, 0, "PHP", "Pascal");
document.write("<br>add element in an array using splice()<br>");
for (i = 0; i < a.length; i++) {
document.write(a[i] + "<br>");
}
break;
case "M":
var a1 = a.slice(1);
document.write("<br>Slice: This method slices out a piece of an array
into a new array.<br>");
for (i = 0; i < a.length; i++) {
document.write(a1[i] + "<br>");
}
break;
default:
document.write("<br>");
document.write("Such Color is not available");
}
</script>
</body>
</html>

5.Write a program to Accept the marks of 10 subjects from the user and
store it in array. Sort them and display
Ans:
<html>
<body>
<h2>Accept and Display the marks</h2>
<script>
a = new Array();
var b = 1;
length = prompt("For how many subjects do you want to enter a marks?");
alert("Enter Marks of Subjects");
for (i = 0; i < length; i++) {
a[i] = prompt("Enter marks of subject " + b);
b++;
}
document.write("<br/><br/>The entered subjects marks are<br\>");
b = 1;
for (i = 0; i < length; i++) {
document.write("Marks of subject " + b + " is :" + a[i]);
document.write("</br>");
b++;
}
document.write("<br/><br/>The array sorted subjects mareks are<br\>");
a.sort();
document.write("<br/>The element in the array are<br\>");
b = 1;
for (i = 0; i < a.length; i++) {
document.write("Marks of subject " + b + " is :" + a[i]);
document.write("</br>");
b++;
}
</script>
</body>
</html>

6.Write a program to perform all the string operations.


Ans:
<html>
<head>
<title>Array Operation</title>
</head>
<body>
<script type="text/javascript">
document.write("<br>Select the operations you want to perform on
string");
document.write("<br>A. indexOf() method");
document.write("<br>B. lastIndexOf() method");
document.write("<br>C. search() method");
document.write("<br>D. slice() method");
document.write("<br>E. Substring() method");
document.write("<br>F. Substr() method");
document.write("<br>G. replace() method");
document.write("<br>H. toUpperCase() method");
document.write("<br>I. toLowerCase() method");
document.write("<br>J. concat() method");
document.write("<br>K. trim() method");
document.write("<br>L. charAt(position) method");
document.write("<br>M. charCodeAt() method");
document.write("<br>N. parseInt(),parseFloat() method");
document.write("<br>O. toString() method");
var choice=prompt("Enter your choice");
alert("You have selected option"+choice)
switch(choice)
{
case "A":
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
document.write("<br>index of locate is:"+pos+"<br>");
break;
case "B":
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
document.write("</br>last index of locate is:"+pos+"<br>");
break;
case "C":
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
document.write("<br>Search result is"+pos+"<br>");
break;
case "D":
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
document.write("<br>Result of Slice method is:"+res+"<br>");
break;
case "E":
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
document.write("<br>Result of substring() method is:"+res+"<br>");
break;
case "F":
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);
document.write("<br>Result of substr() method is:"+res+"<br>");
break;
case "G":
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
document.write("<br>Result of replace() method is:"+res+"<br>");
break;
case "H":
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted
to upper
document.write("<br>Result toUpperCase() method is:"+text2+"<br>");
break;
case "I":
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 converted
to lower
document.write("<br>Result toLowerCase() method is:"+text2+"<br>");
break;
case "J":
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);
document.write("<br>Result concat() method is:"+text3+"<br>");
break;
case "K":
var str = " Hello World! ";
document.write("<br>Result trim() method is:"+str.trim()+"<br>");
break;
case "L":
var str = "HELLO WORLD";
document.write("<br>Result charAt() method:"+str.charAt(0)+"<br>");
break;
case "M":
var str = "HELLO WORLD";
document.write("<br>Result charCodeAt(0)method
is:"+str.charCodeAt(0)+"<br>");
break;
case "N":
document.write("<br>Result parseInt(),parseFloat() method
is:"++"<br>");
break;
case "O":
document.write("<br>Result toString() method is:"++"<br>");
break;
default:
document.write("<br>");
document.write("Such Color is not available");
} </script>
</body>
</html>
7.Write a program to design a form and handle onload Event.
Ans:
<html>
<head>
<title>Demo of onload Tag Attribute</title>
<script type="text/javascript">
function my_fun() {
alert("Welcome");
}
</script>
</head>
<body onload="my_fun()"></body>
</html>

8.Write a program to design a form and handle any 2 mouse Events.


Ans:
<html>
<head>
<title>Demo of mouse event Tag Attribute</title>
<script type="text/javascript">
function my_fun() {
alert("Hello I am in my function");
}
</script>
</head>
<body>
<center>
<form>
<input type="button" value="Double Click" ondblclick="my_fun()" />
</form>
</center>
</body>
</html>

9.Write a program to design a form and handle any 2 Key Events.


Ans:
<html>
<head>
<title>Demo of key event Tag Attribute</title>
<script type="text/javascript">
function my_fun() {
alert("you pressed the key");
}
function my_fun1() {
alert("you pressed the key down");
}
</script>
</head>
<body>
<center>
<form>
On Key Press and Key Down Events Events<br />
Enter Name:<input type="text" onkeypress="my_fun()" /> Enter Roll
No:<input type="text" onkeydown="my_fun1()" />
</form>
</center>
</body>
</html>

10.Write a function to delete a cookie.


Ans:
<html>
<head>
<script type="text/javascript">
function deleteCookie() {
var cookie_value = username.value;
document.cookie = "username=" + cookie_value + ";expires=Thu, 01 Jan
1970 00:00:01 GMT";
alert("Cookie is deleted");
}
</script>
</head>
<body>
Enter Username:<input type="text" id="username" />
<input type="button" value="Delete Cookie" onclick="deleteCookie()" />
</body>
11.Write a JavaScript for creating a cookie for the user name
Ans:
<html>
<head>
<script type="text/javascript">
function createcookie() {
with (document.form1) {
var cookie_value = username.value;
document.cookie = "username=" + cookie_value;
alert("Cookie is Created");
}
}
</script>
</head>
<body>
<form name="form1">
Enter Name:<input type="text" name="username" />
<input type="button" value="Create Cookie" onclick="createcookie()" />
</form>
</body>
</html>

12.write a javascript code to change the content of a specific element in


window
Ans:
<html>
<head>
<script type="text/javascript">
function changecontent() {
document.getElementById("para").innerHTML = "After Clicking the
Button:New Content";
}
</script>
</head>
<body>
<p>Click to change the content of paragraph</p>
<input type="button" value="Change Content" onclick="changecontent()" />
<h3><p id="para">Before Clicking the Button:Old Content</p></h3>
</body>
</html>

13.Write a program to perform form validation for a


registration form using regular expressions Javascript Form
Validation: Alphabetic Data Input
Ans:
<html>
<head>
<title>JavaScript Form Validation: Valid Zip Code</title>
<style>
body {
font-family: Verdana;
}
</style>
</head>

<body>
<script>
function check_Alpha(letters) {
var regex = /^[a-zA-Z]+$/;
if (letters.yourname.value == null) {
alert("Name Field cannot be left empty");
letters.yourname.focus();
return false;
} else if (regex.test(letters.yourname.value) == false) {
alert("Name must be in alphabets only");
letters.yourname.focus();
return false;
} else {
alert("Name is:" + letters.yourname.value);
}

return true;
}
</script>
<form name="alphavalidate" action="#" method="post"
onSubmit="return check_Alpha(this)">
Name :
<input type="text" size="40" name="yourname" />

<input type="submit" value="Submit" />


<input type="reset" />
</form>
</body>
14.Which methods are used for generating the rollover effect. State the
syntax
Ans:
<html>
<head>
</head>
<body>
<img src="JellyFish.jpg" onmouseover="src='Koala.jpg'"
onmouseout="src='JellyFish.jpg'" />
</body>
</html>

15.Write a program to demonstrate the example of image rollover


Ans:
<html>
<body>
<h4>image Rollover</h4>
<img src="Jellyfish.jpg" onmouseover="src='Koala.jpg'"
onmouseout="src='Jellyfish.jpg'" />
</body>
</html>

16.Write a program to demonstrate the example of text rollover


Ans:
<html>
<body>
<h2>Text Rollover</h2>
<h3 onmouseover="document.image.src='Jellyfish.jpg'">Jelly Fish</h3>
<h3 onmouseover="document.image.src='Koala.jpg'">Koala</h3>
<a><img src="Jellyfish.jpg" name="image" /></a>
</body>
</html>

17.Write a program to design drop down menu using JavaScript.


Ans:
<html>
<head>
<script>
function myFunction() {
var select = document.getElementById("student");
var x = document.getElementById("mySelect").value;
if (x == "Select Subject") {
alert("Please select subject");
} else {
document.getElementById("demo").innerHTML = "You Selected:" + x;
}
}
</script>
</head>
<body>
<br />
<br />
<br />
<p>Folating Menu,Scroll Down</p>
<select id="mySelect" style="position: fixed;">
<option value="Select Subject">Select Subject</option>
<option value="OOP">OOP</option>
<option value="CGR">CGR</option>
<option value="DBMS">DBMS</option>
<option value="DSU">DSU</option>
<option value="DTE">DTE</option>
</select>
<br />
<br />
<input type="button" value="Submit" onclick="myFunction()" />
<br />
<p id="demo"></p>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</body>
</html>

18.Write a JavaScript program that creates a scrolling text on the status


line of a window.
Ans:
<html>
<head>
<title>Javascript ScrollText</title>
<script language="javascript">
var statbarmsg = "Hello Friends!" + "Welcome To Javascript";
function scrollStatusBarMsg() {
window.status = statbarmsg;
statbarmsg = statbarmsg.substring(1, statbarmsg.lenght) +
statbarmsg.substring(0, 1);
setTimeout("scrollStatusBarMsg()", 150);
}
</script>
</head>
<body onload="scrollStatusBarMsg()">
<p>Scrolling Message Example</p>
<p>Look at the status line at the bottom of the page</p>
</body>
</html>

19.Write a JavaScript program to disable right click of mouse.


Ans:
<html>
<head>
<script>
document.addEventListener("contextmenu", (event) =>
event.preventDefault());
</script>
</head>
<body>
<h3><p>Disabling the right click of mouse button</p></h3>
</body>
</html>

20.Develop a JavaScript Program to Create Rotating Banner Ads with URL


Links
Ans:
<html>
<head>
<script>
banner_array = new Array("JellyFish.jpg", "Koala.jpg");
link_array = new Array("https://www.google.com",
"https://www.facebook.com");
banner = 0;
function DisplayBanners() {
if (document.images) {
banner++;
if (banner == banner_array.length) {
banner = 0;
}
document.ChangeBanner.src = banner_array[banner];
setTimeout("DisplayBanners()", 5000);
}
}
function display_page() {
document.location.href = link_array[banner];
}
</script>
<body onload="DisplayBanners()">
<center>
<a href="Javascript:display_page()">
<img src="JellyFish.jpg" width="100%" height="500px"
name="ChangeBanner" />
</a>
</center>
</body>
</head>
</html>

21.Create a slideshow with the group of four images, also simulate


the next and previous transition between slides in your JavaScript.
Ans:
<html>
<head>
<script>
img_array = new Array("JellyFish.jpg", "Koala.jpg");
img = 0;
function Displayimg(num) {
img = img + num;
if (img > img_array.length - 1) {
img = 0;
}
if (img < 0) {
img = img_array.length - 1;
}
document.Slide.src = img_array[img];
}
</script>
</head>
<body>
<center>
<img src="JellyFish.jpg" width="400%" height="220" name="Slide"
/><br />
<input type="button" value="Previous" onclick="Displayimg(-1)" />)
<input type="button" value="Next" onclick="Displayimg(1)" />)
</center>
</body>
</html>

IMP Points:
1) Length Method

The length method is used to calculate the length of the string.


Syntax:
string_variable.length();
The length method returns the length of the string, including white spaces.
Eg:
var str = "Hello Cybrosys";
var str_len = str.length();
console.log("length", str_len);

In the console, we see the value 14, which includes 13 characters and 1 white
space.

2) CharAt Method

The charAt method is used to get the character at the specified index of the string.
In a string, the count starts from position zero. So, in order to get the first element
of a string, we should return the index 0.
Syntax:
string_variable.charAt(‘index’);
The charAt method returns the character at the index mentioned.
Eg:
var str = "Hello Cybrosys";
var char_at = str.charAt(6);
console.log(char_at);

Consoling this we get the value ‘C’, which is the character at the 6th position.

3) IndexOf Method

The indexOf method returns the index of the first occurrence of the character or
characters passed. If the passed character is not present in the string, then the
function returns -1.
Syntax:
string_variable.indexOf(‘characters’);
If the characters are present in the string_variable, the method returns the index
of the first occurrence of the characters, else it returns -1.
Eg:
Case: 1
var str = "Hello Cybrosys";
var index_char = str.indexOf('sys');
console.log(index_char);
The console gives value 11 as the first occurrence of ‘sys’ occurs at the 11th index.
Case: 2
var str = "Hello Cybrosys";
var index_char = str.indexOf('xyz');
console.log(index_char);
The console gives value -1 as the string does not contain the characters ‘xyz’.
4) Replace Method

The replace method searches the string for the first occurrence of the first
argument passed and replaces it with the second argument. If the searched
argument is not present in the string, the function returns the string itself.
Syntax:
string_variable.replace(‘first_value’, ‘second_value’);
Eg:
Case 1:
var str = "Hello Cybrosys";
var replace_expr = str.replace('Hello', Hai);
console.log(replace_expr);
The console gives ‘Hai Cybrosys’, because the function replaced the first argument
‘Hello’ with ‘Hai’.
Case 2:
var str = "Hello Cybrosys";
var replace_expr = str.replace('Hai', 'Bye');
console.log(replace_expr);

The console gives ‘Hello Cybrosys’, because the function was unable to find ‘Hai’,
so it returns the string itself.
Case 3:
var str = "Hello Cybrosys Hello";
var replace_expr = str.replace('Hello', 'Hai');
console.log(replace_expr);

The console gives ‘Hai Cybrosys Hello’, because the function replaces the first
occurrence of ‘Hello’ from the string.

5) Slice Method

In the slice method, we pass two indices. The first argument is the starting index,
and the second argument is the ending index. The method slices the string
between these indices and returns it.
Syntax:
string_variable.slice(‘start index’, ‘end index’);
Eg:
var str = "Hello Cybrosys";
var slice_expr = str.slice('6', '11');
console.log(slice_expr);
The console gives ‘Cybro’, that is from the 6th position of the string to the 11th
position of the string.
When we pass only one argument to the function, the function takes the
argument as the starting index and returns the string from the start index to the
end of the string.

6) Split Method

The split method splits the string into an array of substrings, excluding the
arguments passed to it, and returns the array. We can also pass a limit to limit the
elements in the array returned.
Syntax:
string_variable.split(‘character’, ‘limit’)
Eg:
var str = "Hello Cybrosys";
var split_expr = str.split(' ');
console.log(split_expr);
The console gives an array of two elements ‘Hello’ and ‘Cybrosys’. If I pass a limit
1, then an array containing only one element will be passed. In this case, an array
with the element ‘Hello’ is passed.

7) Substr Method

The substr method is used to extract the characters between the given index. The
extracted characters will begin from the ‘start value,’ and extraction ends
according to the length passed with the method.
Syntax:
string_variable.substr(‘start_index’, ‘length’)
Eg:
var str = "Hello Cybrosys";
var substr_expr = str.substr(6, 8);
console.log(substr_expr);
In this case, the console gives us the value ‘Cybrosys’. The Substr method
extracted the string from the 6th index and length 8.
If the length exceeds the count of the string, then all characters after the index is
returned. The same happens if we don’t mention the length.

8) Substring Method

The substring method extracts the string from the start index up to the end index
passed in the method. If the start value is greater than the end value, the method
interchanges the arguments and performs the function.
Syntax:
string_variable.substring(‘start_index’, ‘end_index’);
Eg:
var str = "Hello Cybrosys";
var substring_expr = str.substr(13, 5);
console.log(substring_expr);
Here, the console gives us the value ‘Cybrosys’. The start and end indices are
interchanged here for the function to work.

9) ToLowerCase Method

The toLowerCase method converts the string to lowercase letters.


Syntax:
string_variable.toLowerCase();
Eg:
var str = "Hello Cybrosys";
var toLowerCase_expr = str.toLowerCase();
console.log(toLowerCase_expr);
Here, the console gives us the value “hello cybrosys”. The uppercase letters are
changed to lowercase letters.

10) ToUpperCase Method

The ToUpperCase method is like the inverse of the toLowerCase method. It


converts the string to uppercase letters.
Syntax:
string_variable.toUpperCase();
Eg:
var str = "Hello Cybrosys";
var toUpperCase_expr = str.toUpperCase();
console.log(toUpperCase_expr);

Here, the console gives us the value “HELLO CYBROSYS”. The lowercase letters
are changed to uppercase letters.
So, these are the most commonly used string methods in JavaScript. Now that
you have gone through this blog, I hope you get the idea of string methods, their
difference, and how to use them in JS.

11) Javascript Array.push() Method:


Adding Element at the end of an Array. As arrays in JavaScript are mutable
objects, we can easily add or remove elements from the Array. And it
dynamically changes as we modify the elements from the array.

Syntax :
Array.push(item1, item2 …)

Parameters: Items to be added to an array.


12) JavaScript Array.unshift() Method:
This method is used to add elements to the front of an Array.

Syntax :
Array.unshift(item1, item2 …)

Parameters: Items to be added to the array

13) JavaScript Array.pop() Method:


This method is used to remove elements from the end of an array.

Syntax:
Array.pop();

Parameters: It takes no parameter

14) JavaScript Array.shift() Method:


This method is used to remove elements from the beginning of an
array

Syntax :
Array.shift()

Parameter: it takes no parameter


15) JavaScript Array.splice() Method:
This method is used for the Insertion and Removal of elements in
between an Array

Syntax:
Array.splice (start, deleteCount, item 1, item 2….)

Parameters:
 Start: Location at which to perform the operation.
 deleteCount: Number of elements to be deleted, if no element
is to be deleted pass 0.
 Item1, item2 …..: this is an optional parameter.

16) Create a Cookie with JavaScript:

 JavaScript can create, read, and delete cookies with


the document.cookie property.

 With JavaScript, a cookie can be created like this:

 document.cookie = "username=John Doe";

 You can also add an expiry date (in UTC time). By default, the cookie is
deleted when the browser is closed:

 document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00


UTC";

 With a path parameter, you can tell the browser what path the cookie
belongs to. By default, the cookie belongs to the current page.
 document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00
UTC; path=/";

17) Delete a Cookie with JavaScript:

 Deleting a cookie is very simple.

 You don't have to specify a cookie value when you delete a cookie.

 Just set the expires parameter to a past date:

 document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;


path=/;";

18) RegExp Object:

 A regular expression is a pattern of characters.

 The pattern is used to do pattern-matching "search-and-replace" functions on


text.

 In JavaScript, a RegExp Object is a pattern with Properties and Methods.

 Syntax:

/pattern/modifier(s);

 Example explained:

w3schools The pattern to search for

/w3schools/ A regular expression


/w3schools/i A case-insensitive regular expression

 Modifiers:

Modifiers are used to perform case-insensitive and global searches:

Modifier Description

g Perform a global match (find all matches rather


than stopping after the first match)

i Perform case-insensitive matching

m Perform multiline matching

 Brackets:

Brackets are used to find a range of characters:

Expression Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets


[0-9] Find any character between the brackets (any digit)

[^0-9] Find any character NOT between the brackets (any


non-digit)

(x|y) Find any of the alternatives specified

 Metacharacters:

Metacharacters are characters with a special meaning:

Metacharacter Description

. Find a single character, except newline or line terminator

\w Find a word character

\W Find a non-word character

\d Find a digit

\D Find a non-digit character

\s Find a whitespace character


\S Find a non-whitespace character

\b Find a match at the beginning/end of a word, beginning like


this: \bHI, end like this: HI\b

\B Find a match, but not at the beginning/end of a word

\0 Find a NULL character

\n Find a new line character

\f Find a form feed character

\r Find a carriage return character

\t Find a tab character

\v Find a vertical tab character

\xxx Find the character specified by an octal number xxx

\xdd Find the character specified by a hexadecimal number dd


\udddd Find the Unicode character specified by a hexadecimal
number dddd

 RegExp Object Properties:

Property Description

constructor Returns the function that created the RegExp object's prototype

global Checks whether the "g" modifier is set

ignoreCase Checks whether the "i" modifier is set

lastIndex Specifies the index at which to start the next match

multiline Checks whether the "m" modifier is set

source Returns the text of the RegExp pattern

 RegExp Object Methods

Method Description
compile() Deprecated in version 1.5. Compiles a regular expression

exec() Tests for a match in a string. Returns the first match

test() Tests for a match in a string. Returns true or false

toString() Returns the string value of the regular expression

19)peventDefault():

 The preventDefault() method cancels the event if it is cancelable, meaning


that the default action that belongs to the event will not occur.

 For example, this can be useful when:

 Clicking on a "Submit" button, prevent it from submitting a form


 Clicking on a link, prevent the link from following the URL

 Note: Not all events are cancelable. Use the cancelable property to find out if
an event is cancelable.

 Note: The preventDefault() method does not prevent further propagation of


an event through the DOM. Use the stopPropagation() method to handle this.

 Syntax:

event.preventDefault();

20)setTimeout():
 The setTimeout() method calls a function after a number of
milliseconds.
 1 second = 1000 milliseconds.

 The setTimeout() is executed only once.

 If you need repeated executions, use setInterval() instead.

 Use the clearTimeout() method to prevent the function from


starting.

 To clear a timeout, use the id returned from setTimeout():

 Syntax: myTimeout = setTimeout(function, milliseconds);

 Syntax:

setTimeout(function, milliseconds, param1, param2, ...)

 Parameters:

Parameter Description

function Required.
The function to execute.
milliseconds Optional.
Number of milliseconds to wait before executing.
Default value is 0.

param1, Optional.
param2, Parameters to pass to the function.
... Not supported in IE9 and earlier.

21)setInterval():
 The setInterval() method calls a function at specified intervals (in
milliseconds).

 The setInterval() method continues calling the function until


clearInterval() is called, or the window is closed.

 1 second = 1000 milliseconds.

 To execute the function only once, use the setTimeout() method


instead.

 To clear an interval, use the id returned from setInterval():

 myInterval = setInterval(function, milliseconds);

 Then you can to stop the execution by calling clearInterval():


 clearInterval(myInterval);

 Syntax:

setInterval(function, milliseconds, param1, param2, ...)

 Parameters:

Parameter Description

function Required.
The function to execute

milliseconds Required.
The execution interval.
If the value is less than 10, 10 is used

param1, param2, ... Optional.


Additional parameters to pass to the function
Not supported in IE9 and earlier.

You might also like