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

WEB Module 3

This document covers event handling and the Document Object Model (DOM) in JavaScript, emphasizing the importance of events in creating interactive web applications. It explains various event types, such as onclick, onsubmit, and keyboard events, along with methods like addEventListener and removeEventListener for managing event listeners. Additionally, it discusses the Window object and its methods, including alert and focus, which are essential for user interaction in web browsers.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

WEB Module 3

This document covers event handling and the Document Object Model (DOM) in JavaScript, emphasizing the importance of events in creating interactive web applications. It explains various event types, such as onclick, onsubmit, and keyboard events, along with methods like addEventListener and removeEventListener for managing event listeners. Additionally, it discusses the Window object and its methods, including alert and focus, which are essential for user interaction in web browsers.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 127

WEB

TECHNOLOGIES

Module 3
Module 3
Event Handling and Document Object model in
JavaScript, Handling strings and working with
window object
JAVA SCRIPT EVENTS AND EVENT
LISTENERS
Introduction

• Event-driven: code executed resulting to user or browser action.


• Event: a notification that something specific occurred -- by
browser or user.
• Event handler: a script implicitly executed in response to event
occurrence.

4
onclick Event Type
• This is the most frequently used event type which occurs when a
user clicks the left button of his mouse. You can put your validation,
warning etc., against this event type.
• One attribute can appear in several different tags:
e.g. onClick can be in <a> and <input>
• HTML element get focus:
1. When user puts mouse cursor over it and presses the left button
2. When user tabs to the element
3. By executing the focus method
4. Element get blurred when another element gets focus
5
• Event handlers can be specified two ways
1. Assigning the event handler script
to an event tag attribute
onClick = "alert('Mouse click!');"
onClick = "myHandler();
2. Assigning them to properties of JavaScript object
associated with HTML elements.
• The load event: the completion of loading of a document by
browser
• The onload attribute of <body> used to specify event handler
• The unload event: used to clean up things before a document
is unloaded.
6
Example:
<!DOCTYPE html>
<html><head>
<script type="text/javascript"></script></head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()"
value="Say Hello" />
</form>
</body></html>
7
onSubmit Event Type

• onSubmit is an event that occurs when you try to submit a


form.
• You can put your form validation against this event type.
• Here we are calling a validate function before submitting a form
data to the webserver.
• If validate function returns true, the form will be submitted,
otherwise it will not submit the data.

8
<!DOCTYPE html> Example:
<html><head>
<script type="text/javascript">
</script>
</head><body>
<form method="POST" action="target.html" onsubmit="return validate()">
<input type="submit" value="Submit" />
</form>
</body>
</html>

9
<html>
validation
<head></head>
<body> <center>
<h1 style="color: green;">
Validation program
</h1>
<h3>
Validate Input Fields in HTML Form
</h3> <form action="#" method="post">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname"
placeholder="Enter your first name" required minlength="2">
<br><br>

<label for="password">Password:</label>
<input type="password" name="password" id="password"
placeholder="Enter a secure password" required
minlength="8">
<br><br>
<input type="submit" value="Submit">
</form> </center></body>
Event List

1
Focus & Event Example:
[fig.1 Before Click On That Button]
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<h1>Hello How Are You...?</h1>
<form>
Click This Button<br/>
<input type="button" value="Click Me!" onclick="myFun()"/><br/>
<input type="text" id="username" onfocus="this.blur()"/>
<br/>
</form> [fig.2 After Click On That Button]
<script type="text/javascript">
function myFun()
{
document.getElementById("username").value="shree";
}
</script>
</body>
</html>
addEventListener
• The Event Target method addEventListener() sets up a
function that will be called whenever the specified
event is delivered to the target.
• Common targets are Element, Document, and Window, but the
target may be any object that supports events (such as XML Http
Request).

• addEventListener() works by adding a function or an object


that implements Event Listener to the list of event listeners for
the specified event type on the Event Target on which it's called.

1
Syntax
target.addEventListener(type, listener[, options]);
target.addEventListener(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture,
wantsUntrusted ]);
document.getElementById("myBtn").addEventListener("click",
displayDate);

1
removeEventListener
• The EventTarget.removeEventListener() method removes
from the EventTarget an event listener previously
registered with EventTarget.addEventListener().

1
Syntax
target.removeEventListener(type, listener[, options]);
target.removeEventListener(type, listener[, useCapture]);

1
Other Example Of Events
<!DOCTYPE html>
<html>
<head><title>Display Page</title></head>
<body>
<hr color="orange" />
<center><h1 id="htag">Welcome To ADIT</h1></center>
<hr color="blue" />
<center><button type="button" onclick="Change()">Change</button>
<button type="button" onclick="Hide()">Hide</button>
<button type="button" onclick="Display()">Display</button>
<button type="button" onclick="ChangeColor()">Color Change</button></center>
<hr color="green" />
<script type="text/javascript"> function Change()
{ document.getElementById("htag").innerHTML="Welcome ABC"; } function
Display()
{ document.getElementById("htag").style.display="block"; } function Hide()
{ document.getElementById("htag").style.display="none"; } function
ChangeColor()
{ document.getElementById("htag").style.color="blue"; }
</script>
</body>
</html>
Output

[fig.3 Initial [fig.4 When Click On Change


Page] Or Display]

[fig.5 When Click [fig.6 When Click On


On Hide] Color Change]

1
Event Listeners
• Event listeners are the foundation of event handling
in the DOM.
• An event listener is a function that waits for a
specific event to occur on an HTML element and
executes a set of instructions when the event is
triggered.
example:
const button = document.querySelector('button');
button.addEventListener('click', () => {
alert('Button clicked!');
});
• we first select a button element using the querySelector()
method.
• We then attach an event listener to the button using the
addEventListener() method.
• The event we're listening for is 'click', and the function we
want to execute when the event occurs is an anonymous
function that displays an alert message.
Using DOM and Events:

•Suppose we want to make changes in the document or stylesheet on a


certain event.
•The event can be the loading of a web page, selection of any specific element
or a form is submitted, etc.
•Some common event attributes are as follows.
Event Handling in JavaScript

• JavaScript Events are actions or occurrences that happen


in the browser.
• Event handling is a key concept in JavaScript, enabling
interactivity by responding to user actions like clicks,
keypresses, or scrolling
Event Handling in DOM
• Event handling in the DOM (Document Object Model) is the
process of detecting and responding to user interactions or
system events on a web page.
• Events can be triggered by a variety of actions, such as clicking a
button, submitting a form, scrolling the page, or resizing the
window.
• Event handling allows web developers to create dynamic and
interactive user interfaces that respond to user input in real-time.
DOM (Document Object Model)

• It is a programming interface that is used to connect web


pages to scripts by representing the structure of a
document such as HTML documents.
• It defines the way a document is to be accessed and
manipulated and also defines the logical structure of
documents.
What is DOM?

The Document Object Model (DOM) is a cross-platform and
language-independent application programming interface.

The DOM, is the API through which JavaScript interacts with
content within a website.

The DOM API is used to access, traverse and
manipulate HTML and XML documents.
HTML DOM Tree Objects
● Window Event Attributes: These events are triggered for the window object.
○ onload: It fires after the page is finished loading.
○ onresize: It fires when the browser window is resized.
● Mouse Events: These are the most common events with basic interaction of
user through the mouse.
○ onclick: It fires when a mouse click is triggered on an element.
○ onmouseover: It fires when a mouse pointer moves over an
element.
○ ondblclick: It fires on a mouse double click on the element
● KeyBoard Events:
○ onkeydown: It fires when the user is pressing a specific key
○ onkeyup: It fires when a user releases a specific key
// Mouse Event
document.addEventListener("mousemove", (e) => {
console.log(`Mouse moved to (${e.clientX}, ${e.clientY})`);
});

// Keyboard Event
document.addEventListener("keydown", (e) => {
console.log(`Key pressed: ${e.key}`);
});

● The mousemove event tracks cursor movement.


● The keydown event captures key presses.
1. Mouse Events
Mouse events are some of the most commonly used events in web development.
Here's an example of how to handle a click event:

we're listening for a click event on a button element, and displaying an alert message
when the button is clicked.
2. Keyboard Events

Keyboard events are another important type of event in the DOM.

we're listening for a keypress event on the entire document. When a key is pressed, the
event object is passed to the callback function, and we display a message in the console
that shows which key was pressed.
3. Form Events
Form events are used to handle interactions with HTML form elements.

we're listening for a submit event on a form element. When the form is submitted, we prevent
the default behavior (which is to reload the page), and display the value of the input field in the
console.
4 Window Events
Window events are used to handle interactions with the browser window.

window.addEventListener('resize', () => {

console.log(`Window size changed to ${window.innerWidth}

x${window.innerHeight}`);

});

we're listening for a resize event on the window object. When the window is resized, we
display the new width and height of the window in the console.
5. Touch Events

Touch events are used to handle interactions with touchscreens on mobile devices. Here's an
example of how to handle a touchstart event:

const box = document.querySelector('.box');

box.addEventListener('touchstart', (event) => {


console.log(`Touch started at (${event.touches[0].clientX},$
{event.touches[0].clientY})`);
});

we're listening for a touchstart event on a box element. When the user touches the box, we
display the coordinates of the touch in the console.
Removing Event Listeners

To remove an event listener, use the removeEventListener() method. This is useful when
you no longer need the event handler to execute, such as when components are removed
from the DOM.

Example:

const handleClick = () => {


alert('Button clicked!');
};

button.addEventListener('click', handleClick);

// Later in the code


button.removeEventListener('click', handleClick);
check if given NUMBER is valid or invalid. example
const isNum = n =>
typeof n === 'number' && !isNaN(n);
console.log(isNum(42));
console.log(isNum('42'));
console.log(isNum(NaN));

Output:
example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handling</title>
<style>
body { text-align: center; font-family: Arial, sans-serif; }
</style>
</head>
<body>
<h2>Click the Button</h2>
<button id="btn">Click Me</button>
<p id="msg"></p>

<script>
document.getElementById("btn").addEventListener("click", function() {
document.getElementById("msg").textContent = "Button Clicked!";
});
</script>
</body>
Output
Add text

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>DOM Methods Example</title>
<style> body { text-align: center; font-family: Arial, sans-
serif; }
</style></head><body>
<h2>DOM Methods Example</h2>
<button id="btn">Click Me</button>
<p id="msg"></p>
<button id="addText">Add Text</button>
<div id="container"></div>
<body>
<h2>DOM Methods Example</h2>
<button id="btn">Click Me</button>
<p id="msg"></p>
<button id="addText">Add Text</button>
<div id="container"></div><script>
// Changing text content on button click
document.getElementById("btn").addEventListener("click", function() {
document.getElementById("msg").textContent = "Button Clicked!";
});

// Adding a new paragraph dynamically


document.getElementById("addText").addEventListener("click",
function() {
let newPara = document.createElement("p");
newPara.textContent = "This is a new paragraph added
dynamically!";
document.getElementById("container").appendChild(newPara);
});
</script></body></html>
Output
Dynamic Content
<html>
<body>
<h2>Dynamic Content</h2>
<button id="button">Add Element</button>
<script>
document.querySelector("#button").addEventListener("click", () => {
let newDiv = document.createElement("div");
newDiv.textContent = "New Element Added";
newDiv.style.margin = "10px 0";
document.body.appendChild(newDiv);
});
</script>
</body>
</html>
Interactive List
<html>
<body>
<h2>Interactive Lists</h2>
<ul id="lists">
<li>Interactive Item 1</li>
<li>Interactive Item 2</li>
<li>Interactive Item 3</li>
</ul>
<script>
let ul = document.querySelector("#lists");
ul.addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
e.target.style.backgroundColor = "yellow";
}
});
</script>
</body></html>
Window Object in Javascript?
Window Object in Javascript?
• The Window object represents the window in
the browser.
• The window object is automatically created
from the browser.
• All browsers support the Window object.
• The window object methods are used to
retrieve the information from the browser
window.
Window object Methods
alert()
• The alert() method displays the alert box in the window with the OK
button. This method is used when you want the information to come
through the user.
alert("Hello...Most welcome");

• The alert() method displays an alert box with a message and an OK


button.
• The alert() method is used when you want information to come
through to the user
EXAMPLE
<body>
<h1>The Window Object</h1>
<h2>The alert() Method</h2>
<p>Click the button to display an alert box.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("Hello! I am an alert box!");
}
</script>
</body>
OUTPUT
focus()

• The focus() method focuses on the window.

• const myWindow = window.open("", "",


"width=250, height=200");
myWindow.focus();

• The focus() method sets focus to a window.


• The blur() method removes focus from a window.
EXAMPLE
<body>

<h1>The Window Object</h1>


<h2>The focus() Method</h2>

<p>Click the button to open a new window, and set focus to it.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
const myWindow = window.open("", "", "width=200,height=100");
myWindow.focus();
}
</script>

</body>
setInterval()
• This method calls on a function with a specific
interval.
• setInterval(function, milliseconds, param1,.....)
Example
setInterval(displayHi, 1000);
function displayHi() {
document.getElementById("demo").innerHTML +=
"Hello world";
}
Example
<body> <body>

<h1>The Window Object</h1> <h1>The Window Object</h1>


<h2>The setInterval() Method</h2>
<h2>The setInterval() Method</h2>
<p id="demo"></p>
<p id="demo"></p>
<script>
<script> setInterval(displayHello, 1000);
const element =
document.getElementById("demo"); function displayHello() {
setInterval(function() {element.innerHTML document.getElementById("demo").innerHTML
+= "Hello";
+= "Hello\n"},1000);
}
</script>
</script>

</body> </body>
• 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.
Interval time example
<body>

<h1>The Window Object</h1>


<h2>The setInterval() Method</h2>

<p id="demo"></p>

<script>
setInterval(myTimer, 1000);

function myTimer() {
const date = new Date();
document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
</script>

</body>
clearInterval()

• The clearInterval() method that clears the time set by the setInterval()
method.
• clearInterval(functon_name);
EX
• const mynewInterval = setInterval(mynewTimer, 1000);
function mynewTimer() {
const date = new Date();
document.getElementById("demo").innerHTML =
date.toLocaleTimeString();
}
function mynewStopFunction() {
clearInterval(mynewInterval);
}
Interval and clear interval
<body>
<h1>The Window Object</h1>
<h2>The setInterval() and clearInterval() Methods</h2>
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>
<script>
const myInterval = setInterval(myTimer, 1000);
function myTimer() {
const date = new Date();
document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
function myStopFunction() {
clearInterval(myInterval);
}
</script>
</body>
Interval and clear interval(color)
<body>
<h1>The Window Object</h1>
<h2>The setInterval() and clearInterval() Methods</h2>
<p>In this example, the setInterval() method executes the setColor() function once every 500
milliseconds
to toggle between two background colors.</p>
<button onclick="stopColor()">Stop Toggling</button>
<script>
myInterval = setInterval(setColor, 1000);
function setColor() {
let x = document.body;
x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}
function stopColor() {
clearInterval(myInterval);
}
</script>
</body>
<body>

<h1>The Window Object</h1>


<h2>The setInterval() and clearInterval() Methods</h2>

<p id="demo1"></p>

<p id="demo2" style="color:red;"></p>

<script>
setInterval(function() {myFunc("param1", "param2")}, 2000);

function myFunc(p1, p2) {


document.getElementById("demo1").innerHTML += "Hello";
document.getElementById("demo2").innerHTML = "Parameters: " + p1 + " " + p2;
}
</script>

</body>
Output
setTimeout()

• The setTimeout() method calls a function after a number of


milliseconds. This method calls the function only once.
• setTimeout(function, milliseconds, param1, ...)

const mynewTimeout = setTimeout(mynewGreeting, 5000);


function mynewGreeting() {
document.getElementById("demo").innerHTML = "Happy
Birthday!"
}

• This mynewGreeting() method returns Happy Birthday after 5


seconds
Example
<body>
<h1>The Window Object</h1>
<h2>The setTimeout() and clearTimeout() Methods</h2>
<p>Click "Stop" to prevent myGreeting() to execute. (You have 5
seconds)</p>
<button onclick="myStopFunction()">Stop!</button>
<h2 id="demo"></h2>
<script>
const myTimeout = setTimeout(myGreeting, 5000);
function myGreeting() {
document.getElementById("demo").innerHTML = "hi, welcome to MCA"
}
function myStopFunction() {
clearTimeout(myTimeout);
}
</script>
</body>
Output
• The setTimeout() method calls a function
after a number of milliseconds.
• 1 second = 1000 milliseconds.
clearTimeout()

• The clearTimeout() method that clears the time set by the setTimeout()
method.

• clearTimeout(function_name);
• const mynewTimeout = setTimeout(mynewGreeting, 3000);
function mynewGreeting() {
document.getElementById("demo").innerHTML = "Happy Birthday to
You !!"
}
function mynewStopFunction() {
clearTimeout(mynewTimeout);
}
• We have to clear the timer within the setTimeout() method.
example
<body><h1>The Window Object</h1>
<h2>The setTimeout() and clearTimeout() Methods</h2>
<button onclick="startCount()">Start count!</button>
<input type="text" id="demo">
<button onclick="stopCount()">Stop count!</button>
<p>Click on "Start count!" to start the timer. The input field will count forever, starting at 0.</p>
<p>Click on "Stop count!" to stop counting. Click on "Start count!" to start the timer again.</p>
<script>
let counter = 0;
let timeout;
let timer_on = 0;
function timedCount() {
document.getElementById("demo").value = counter;
counter++;
timeout = setTimeout(timedCount, 1000);
}
function startCount() {
if (!timer_on) {
timer_on = 1;
timedCount();
}}
function stopCount() {
clearTimeout(timeout);
timer_on = 0;
}
</script>
output
close()
The close() method closes the window

window.close()
function closenewWin() {
mynewWindow.close();
}
example1
<body>
<h1>The Window Object</h1>
<h2>The open() and close() Methods</h2>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
let myWindow;
function openWin() {
myWindow = window.open("", "", "width=200,height=100");
}
function closeWin() {
myWindow.close();
}
</script>
</body>
Output
Example 2
<body>
<h1>The Window Object</h1>
<h2>The open() and close() Method</h2>
<button onclick="openWin()">Open w3schools.com in a new window</button>
<button onclick="closeWin()">Close the new window</button>
<script>
let myWindow;
function openWin() {
myWindow = window.open("https://www.w3schools.com", "_blank", "width=500,
height=500");
}
function closeWin() {
myWindow.close();
}
</script>
</body>
Output

After click clear button


open()
• The open() method opens the browser window.
• window.open()
Syntax
• window.open(URL, name, specs, replace)
example
• function mynewFunction() {
window.open("https://www.cybrosys.com");
}
example
<body>
<h1>The Window Object</h1>
<h2>The open() Method</h2>
<p>Click the button to open a new browser window.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
window.open("https://www.w3schools.com");
}
</script>
</body>
Click on button ,it open site
confirm()
• The confirm method displays a dialog box with a
message, Ok button, and Cancel button.
• The confirm() method returns true if the user
clicked "OK", otherwise false.

• Synatx: confirm(message)

• confirm("Click Me!");
• function mynewFunction() {
confirm("Press a button!");
}
example
<body><h1>The Window Object</h1>
<h2>The confirm() Method</h2>
<p>Click the button to see line-breaks in a confirm box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text = "Press a button!\nEither OK or Cancel.";
if (confirm(text) == true) {
text = "You pressed OK!“ THANK YOU;
} else {
text = "You canceled!";
}
document.getElementById("demo").innerHTML = text;
}
output
scrollBy() method
• The scrollBy() method scrolls the document
by the specified number of pixels.
• Syntax: window.scrollBy(x, y)
<!DOCTYPE html>
<html><body><h1>The Window Object</h1>
<h2>The scrollBy() Method</h2>
<p>Click to scroll the document.</p>
<button onclick="scrollWin()" style="position:fixed">Scroll 100px vertically!</button>
<br><br>
<h3>Some line breaks to enable scrolling:</h3>
<br><br><br><p>When I find myself in times of trouble</p>
<br><br><br>
<p>Mother Mary comes to me</p>
<br><br><br>
<p>Speaking words of wisdom, let it be</p>
<br><br><br>
<p>And in my hour of darkness she is standing right in front of me</p>
<br><br><br>
<p>Speaking words of wisdom, let it be</p>
<br><br><br>
<p>ROCK AND ROLL</p>
<br><br><br>
<p>SCROLL SCROLL SCROLL</p>
<br><br><br>
<p>ROCK AND ROLL</p>
<br><br><br>
<p>SCROLL SCROLL SCROLL</p>
<br><br>
<br><p>ROCK AND ROLL</p>
<br><script>
function scrollWin() {
window.scrollBy(0, 100);
}
</script></body></html>
JavaScript String handling
• Strings are for storing text & digit values
• Strings are written with quotes
• JavaScript strings are the sequence of
characters.
• In JavaScript, strings are automatically
converted to string objects when using string
methods on them.
• This process is called auto-boxing.
The following are methods that we can call on strings
• slice()
• substring()
• substr() .
• replace()
• replaceAll() .
• toUpperCase()
• toLowerCase()
• trim() .
• trimStart()
• trimEnd()
• padStart()
• padEnd()
• charAt()
• charCodeAt()
• split()
Extracting String Parts
There are 3 methods for extracting a part of a
string:
• slice(start, end)
• substring(start, end)
• substr(start, length)
slice()

It extracts a part of the string based on the


given stating-index and ending-index and
returns a new string.
• The method takes 2 parameters: start
position, and end position (end not included).
let text = "Apple, Banana, Kiwi";
let a= text.slice(7,13);
let b= text.slice(-12);
let c= text.slice(-12,-6)
let d= text.slice(7);
let e= text.slice(15);

console.log(a);
console.log(b);
console.log(c);
console.log(d);
console.log(e);
Output
• Banana
• Banana, Kiwi
• Banana
• Banana, Kiwi
• Kiwi
Examples
//define the string variable
let text = "Java, Python, C";

//use slice method


let A= text.slice(0,15)
let B= text.slice(0,-1)
let C= text.slice(0,6)
let D= text.slice(6,9)
let E= text.slice(10)
Output
• Java, Python, C
• Java, Python
• Java,
• Pyt
• on, C
substring()

• It returns the part of the given string from


the start index to the end index. Indexing
starts from zero (0).
• substring() is similar to slice().
• The difference is that start and end values
less than 0 are treated as 0 in substring().
example
let str = "Apple,Banana,Kiwi";

let A=str.substring(6,13);
let B=str.substring(7);
let C=str.substring(-4);
let D=str.substring(-20);

console.log(A);
console.log(B);
console.log(C);
console.log(D);
• Banana
• Banana, Kiwi
• Kiwi
• Apple, Banana, Kiwi
substr()

• substr() This method returns the specified


number of characters from the specified
index from the given string. It extracts a part
of the original string.
• substr() is similar to slice(). The difference is
that the second parameter specifies
the length of the extracted part.
let str = "Python, C, C++, JAVA";

let A=str.substring(7,20);
let B=str.substring(-9);
let C=str.substring(1);
let D=str.substring(-7);

console.log(A);
console.log(B);
console.log(C);
console.log(D);
• C, C++, JAVA
• C++, JAVA
• ython, C, C++, JAVA
• +, JAVA
replace()
• It replaces a part of the given string with
another string or a regular expression. The
original string will remain unchanged.
• The replace() method replaces a specified
value with another value in a string:
• The replace() method returns a new string.
• The replace() method replaces only the
first match
let string = 'lang';

let newstring = string.replace('lang', 'web');


let newstring1 = string.replace('lang', 'java');
let newstring2 = string.replace('lang', 'python');

console.log(newstring);
console.log(newstring1);
console.log(newstring2);
• Web
• Java
• python
Example
output
• java is a high level programming language
replaceAll()

• It returns a new string after replacing all the


matches of a string with a specified string or
a regular expression.
• The original string is left unchanged after this
operation.
Example 1

Output
• Mind, Space, Space, Soul
Example 2

Output
apple,vehical,lang,college
Example 3

Output
manglore,Ajiet,Ajiet,web
toUpperCase()

• It converts all the characters present in the


String to upper case and returns a new String
with all characters in upper case.
• This method accepts single parameter string
Variable string that you want to convert in
upper case.
Example

Output
• COLLEGE NAME
• AJIET MANGLORE
toLowerCase()
• It converts all the characters present in the so
lowercase and returns a new string with all
the characters in lowercase.
Example 1
Output
• college name
• aj institute of engineering and technology
• mangalore
concat()
• It combines the text of two strings and
returns a new combined or joined string.
• To concatenate two strings, we use
the concat() method on one object of string
and send another object of string as a
parameter.
• This method accepts one argument.
• The variable contains text in double quotes
or single quotes.
Example 1

Output:
WEB-TECHNOLOGY
Example 2

Output : web techprogramming language


trim()
• It is used to remove either white spaces from
the given string.
• This method returns a new string with
removed white spaces.
• This method is called on a String object.
Example 1

• Output: 4 14
trimStart()
• It removes whitespace from the beginning of
a string.
• The value of the string is not modified in any
manner, including any whitespace present
after the string.
Example 1
Example 2

Output :
trimEnd()
• removes white space from the end of a string.
• The value of the string is not modified in any
manner, including any white-space present
before the string.
Example

Output:
WEB TECH
WEB TECH
padStart()
• padStart() pad a string with another string
until it reaches the given length. The padding
is applied from the left end of the string.

OUTPUT: WEB WTECH


Example 2
charAt()

• It returns the character at the specified index. String in


JavaScript has zero-based indexing.
Example 1
Output
charCodeAt()
• It returns a number that represents
the Unicode value of the character at
the specified index. This method accepts one
argument.
Example 1

Output : 119
97
Example 2
split()
• It splits the string into an array of sub-strings. This
method returns an array.
• This method accepts a single parameter character on
which you want to split the string.
Example 1

Output : [ 'web', 'tech', 'language' ]


Example 2

You might also like