1 of 102

JavaScript

By Atul Bhatt

JS

2 of 102

2

JavaScript

3 of 102

Bring the attention of your audience over a key concept using icons or illustrations

3

JavaScript 

Introduction

4 of 102

What is JavaScript?

JavaScript is a very powerful client-side scripting language. JavaScript is used mainly for enhancing the interaction of a user with the webpage. In other words, you can make your webpage more lively and interactive, with the help of JavaScript. JavaScript is also being used widely in game development and Mobile application development.

5 of 102

Javascript History

JavaScript was developed by Brendan Eich in 1995, which appeared in Netscape, a popular browser of that time.

The language was initially called LiveScript and was later renamed JavaScript. There are many programmers who think that JavaScript and Java are the same. In fact, JavaScript and Java are very much unrelated. Java is a very complex programming language whereas JavaScript is only a scripting language.

6 of 102

6

JavaScript Introduction

 

JavaScript is the programming language of HTML and the Web.

JavaScript is easy to learn.

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

   1. HTML to define the content of web pages

   2. CSS to specify the layout of web pages

   3. JavaScript to program the behavior of web pages

Did You Know?

JavaScript and Java are completely different languages, both in concept and design.

7 of 102

JavaScript cannot run on its own. In fact, the browser is responsible for running JavaScript code. When a user requests an HTML page with JavaScript in it, the script is sent to the browser and it is up to the browser to execute it. The main advantage of JavaScript is that all modern web browsers support JavaScript. So, you do not have to worry about whether your site visitor uses Internet Explorer, Google Chrome, Firefox or any other browser. JavaScript will be supported. Also, JavaScript runs on any operating system including Windows, Linux or Mac.

How to Run JavaScript?

8 of 102

Download Visual Studio Code

8

Download

9 of 102

9

Monokai-Contrast Theme

NetBeans Light Theme

10 of 102

A Simple JavaScript Program

You should place all your JavaScript code within <script> tags (<script> and </script>) if you are keeping your JavaScript code within the HTML document itself.

<script type="text/javascript">

write() Method

<html>

<body>

<script>

document.write("Hello World!");

</script>

</body>

</html>

<script>

document.write("<h1>Hello World!</h1><p>Have a nice day!</p>");

</script>

11 of 102

Alert Box

An alert box is often used if you want to make sure information comes through to the user.

When an alert box pops up, the user will have to click "OK" to proceed.

<html>

<head>

<title>My First JavaScript code!!!</title>

<script type="text/javascript">

alert("Hello World!");

</script>

</head>

<body>

</body>

</html>

type="text/javascript" is not necessary in HTML5.

12 of 102

JavaScript Where To

In HTML, JavaScript code must be inserted between <script> and </script> tags.

<html>

<body>

<h2>JavaScript in Body</h2>

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

<script>

document.getElementById("demo").innerHTML = "My First JavaScript";

</script>

</body>

</html>

Old JavaScript examples may use a type attribute: <script type="text/javascript">.The type attribute is not required. JavaScript is the default scripting language in HTML.

  1.  getElementById:  To access elements and attributes whose id is set.
  2.  innerHTML: To access the content of an element.

13 of 102

JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a button.

You will learn much more about functions and events in later chapters.

JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an HTML page.

The function is invoked (called) when a button is clicked:

14 of 102

14

<html>

<head>

<script>

function myFunction()

{

document.getElementById("demo").innerHTML = "Paragraph changed.";

}

</script>

</head>

<body>

<h2>JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

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

</body>

</html>

15 of 102

15

<html><body> ��<h1>A Web Page</h1><p id="demo">A Paragraph</p><button type="button" onclick="myFunction()">Try it</button>��<script>function myFunction()

{� document.getElementById("demo").innerHTML = "Paragraph changed.";�}�</script>��</body></html>

JavaScript in <body>

In this example, a JavaScript function is placed in the <body> section of an HTML page.

The function is invoked (called) when a button is clicked:

16 of 102

JavaScript HTML DOM

  • With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
  • The HTML DOM (Document Object Model)
  • When a web page is loaded, the browser creates a Document Object Model of the page.
  • The HTML DOM model is constructed as a tree of Objects:

16

17 of 102

The HTML DOM Tree of Objects�

18 of 102

18

19 of 102

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

  • JavaScript can change all the HTML elements in the page

  • JavaScript can change all the HTML attributes in the page

  • JavaScript can change all the CSS styles in the page

  • JavaScript can remove existing HTML elements and attributes

  • JavaScript can add new HTML elements and attributes

  • JavaScript can react to all existing HTML events in the page

  • JavaScript can create new HTML events in the page

20 of 102

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."

21 of 102

JavaScript Variable: Declare, Assign a Value with Example

Declare Variables in JavaScript

Before using a variable, you first need to declare it. You have to use the keyword var to declare a variable like this:

var name;

Assign a Value to the Variable

You can assign a value to the variable either while declaring the variable or after declaring the variable.

var name = "John";

OR

var name;

name = "John";

22 of 102

22

<html>

<body>

<h2>JavaScript Variables</h2>

<p>In this example, x, y, and z are variables.</p>

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

<script>

var x = 5;

var y = 10;

var z = x + y;

document.getElementById("demo").innerHTML ="The value of z is: " + z;

</script>

</body>

</html>

From the example above, you can expect:

  • x stores the value 5
  • y stores the value 10
  • z stores the value 15

23 of 102

<html>

<head>

<title>Variables!!!</title>

<script type="text/javascript">

var one = 22;

var two = 3;

var add = one + two;

var minus = one - two;

var multiply = one * two;

var divide = one/two;

document.write("First No: = " + one + "<br />Second No: = " + two + " <br />");

document.write(one + " + " + two + " = " + add + "<br/>");

document.write(one + " - " + two + " = " + minus + "<br/>");

document.write(one + " * " + two + " = " + multiply + "<br/>");

document.write(one + " / " + two + " = " + divide + "<br/>");

</script>

</head>

<body>

</body>

</html>

24 of 102

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (like JavaScript keywords) cannot be used as names

JavaScript identifiers are case-sensitive.

25 of 102

JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

26 of 102

Declaring (Creating) JavaScript Variables

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the

var keyword:

var carName;

After the declaration, the variable has no value (technically it has the value of undefined).

To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare it:

var carName = "Volvo";

27 of 102

<body>

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

<script>

var carName = "Volvo";

document.getElementById("demo").innerHTML = carName;

</script>

</body>

28 of 102

<body>

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

<p id="demo2"></p>

<script>

var person = "John Doe", carName = "Volvo", price = 200;

document.getElementById("demo").innerHTML = carName;

document.getElementById("demo2").innerHTML = person;

</script>

</body>

29 of 102

<body>

<h2>JavaScript Variables</h2>

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

<script>

var pi = 3.14;

var person = "John Doe";

var answer = 'Yes I am!';

document.getElementById("demo").innerHTML = pi + "<br>" + person + "<br>" + answer;

</script>

</body>

30 of 102

<script>

var x = "John" + " " + "Doe";

document.getElementById("demo").innerHTML = x;

</script>

John Doe

<body>

<h2>JavaScript Variables</h2>

<p>The result of adding 2 + 3 + "5":</p>

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

<script>

var x = 2 + 3 + "5"

document.getElementById("demo").innerHTML = x;

</script>

</body>

The result of adding 2 + 3 + "5":

55

31 of 102

JavaScript Operators

<body>

<h2>JavaScript Operators</h2>

<p>x = 5, y = 2, calculate z = x + y, and display z:</p>

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

<script>

var x = 5;

var y = 2;

var z = x + y;

document.getElementById("demo").innerHTML = z;

</script>

JavaScript Operators

x = 5, y = 2, calculate z = x + y, and display z:

7

Operator

Description

+

Addition

-

Subtraction

*

Multiplication

32 of 102

JavaScript String Operators

The + operator can also be used to add (concatenate) strings.

<body>

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

<script>

var txt1 = "John";

var txt2 = "Doe";

document.getElementById("demo").innerHTML = txt1 + " " + txt2;

</script>

</body>

33 of 102

JavaScript Arithmetic

Operator

Description

+

Addition

-

Subtraction

*

Multiplication

Arithmetic operators perform arithmetic on numbers (literals or variables).

/

Division

%

Modulus (Remainder)

++

Increment

--

Decrement

Operand

Operator

Operand

100

+

50

Operators and Operands

The numbers (in an arithmetic operation) are called operands.

The operation (to be performed between the two operands) is defined by an operator.

34 of 102

Adding

The addition operator (+) adds numbers:

<body>

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

<script>

var x = 5;

var y = 2;

var z = x + y;

document.getElementById("demo").innerHTML = z;

</script>

</body>

<body>

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

<script>

var x = 5;

var y = 2;

var z = x - y;

document.getElementById("demo").innerHTML = z;

</script>

</body>

Subtracting

The subtraction operator (-) subtracts numbers.

35 of 102

Multiplying

The multiplication operator (*) multiplies numbers.

<body>

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

<script>

var x = 5;

var y = 2;

var z = x * y;

document.getElementById("demo").innerHTML = z;

</script>

</body>

Dividing

The division operator (/) divides numbers.

<body>

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

<script>

var x = 5;

var y = 2;

var z = x / y;

document.getElementById("demo").innerHTML = z;

</script>

</body>

36 of 102

Remainder

The modulus operator (%) returns the division remainder.

<body>

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

<script>

var x = 5;

var y = 2;

var z = x % y;

document.getElementById("demo").innerHTML = z;

</script>

</body>

37 of 102

Incrementing

The increment operator (++) increments numbers.

<body>

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

<script>

var x = 5;

x++;

var z = x;

document.getElementById("demo").innerHTML = z;

</script>

</body>

6

<body>

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

<script>

var x = 5;

x--;

var z = x;

document.getElementById("demo").innerHTML = z;

</script>

</body>

Decrementing

The decrement operator (--) decrements numbers.

4

38 of 102

JavaScript Data Types

JavaScript variables can hold many data types: numbers, strings, objects and more:

var length = 16;                               // Number�var lastName = "Johnson";                      // String�var x = {firstName:"John", lastName:"Doe"};    // Object

The Concept of Data Types

In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the type.

Without data types, a computer cannot safely solve this:

var x = 16 + "Volvo";

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result?

JavaScript will treat the example above as:

var x = "16" + "Volvo";

39 of 102

<body>

<h2>JavaScript</h2>

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

<script>

var x = 16 + "Volvo";

document.getElementById("demo").innerHTML = x;

</script>

</body>

When adding a number and a string, JavaScript will treat the number as a string.

<body>

<h2>JavaScript</h2>

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

<script>

var x = "Volvo" + 16;

document.getElementById("demo").innerHTML = x;

</script>

</body>

Volvo16

16Volvo

40 of 102

JavaScript:

var x = 16 + 4 + "Volvo";

Result:

20Volvo

JavaScript:

var x = "Volvo" + 16 + 4;

Result:

Volvo164

In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".

In the second example, since the first operand is a string, all operands are treated as strings.

JavaScript Types are Dynamic

JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

<body>

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

<script>

var x; // Now x is undefined

x = 5; // Now x is a Number

x = "John"; // Now x is a String

document.getElementById("demo").innerHTML = x;

</script>

41 of 102

JavaScript Strings

A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

<body>

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

<script>

var carName1 = "Volvo XC60";

var carName2 = 'Volvo XC60';

document.getElementById("demo").innerHTML =

carName1 + "<br>" +

carName2;

</script>

<body>

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

<script>

var answer1 = "It's alright";

var answer2 = "He is called 'Johnny'";

var answer3 = 'He is called "Johnny"';

document.getElementById("demo").innerHTML =

answer1 + "<br>" +

answer2 + "<br>" +

answer3;

</script>

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

42 of 102

JavaScript Booleans

Booleans can only have two values: true or false.

<body>

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

<script>

var x = 5;

var y = 5;

var z = 6;

document.getElementById("demo").innerHTML =

(x == y) + "<br>" + (x == z);

</script>

</body>

true�false

Booleans are often used in conditional testing.

43 of 102

The typeof Operator

You can use the JavaScript typeof operator to find the type of a JavaScript variable.The typeof operator returns the type of a variable or an expression:

<body>

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

<script>

document.getElementById("demo").innerHTML =

typeof "" + "<br>" +

typeof "John" + "<br>" +

typeof "John Doe";

</script>

</body>

string�string�string

<body>

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

<script>

document.getElementById("demo").innerHTML =

typeof 0 + "<br>" +

typeof 314 + "<br>" +

typeof 3.14 + "<br>" +

typeof (3) + "<br>" +

typeof (3 + 4);

</script>

</body>

number�number�number�number�number

44 of 102

Undefined

In JavaScript, a variable without a value, has the value undefined. The type is also undefined.

<body>

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

<script>

var car;

document.getElementById("demo").innerHTML =

car + "<br>" + typeof car;

</script>

</body>

undefined�undefined

<body>

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

<script>

var car = "Volvo";

car = undefined;

document.getElementById("demo").innerHTML =

car + "<br>" + typeof car;

</script>

</body>

undefined�undefined

45 of 102

<!DOCTYPE html>

<html>

<body>

<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>

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

</body>

</html>

46 of 102

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

<html>

<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation, and returns the result:</p>

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

<script>

function myFunction(p1, p2)

{

return p1 * p2;

}

document.getElementById("demo").innerHTML = myFunction(4, 3);

</script>

</body>

</html>

JavaScript Functions

This example calls a function which performs a calculation, and returns the result:

12

47 of 102

Why Functions?

You can reuse code: Define the code once, and use it many times.

You can use the same code many times with different arguments, to produce different results.

48 of 102

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas:�(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {  // code to be executed}

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

49 of 102

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

50 of 102

<html>

<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation and returns the result:</p>

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

<script>

var x = myFunction(4, 3);

document.getElementById("demo").innerHTML = x;

function myFunction(a, b)

{

return a * b;

}

</script>

</body>

</html>

JavaScript Functions

This example calls a function which performs a calculation and returns the result:

12

51 of 102

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Functions</h2>

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

<script>

function pop(f)

{

return (5+5) * (f-2);

}

document.getElementById("demo").innerHTML = pop(72);

</script>

</body>

</html>

700

The () Operator Invokes the Function

52 of 102

JavaScript Objects

Object

Properties

Methods

�car.name = Fiat��car.model = 500��car.weight = 850kg��car.color = white

�car.start()��car.drive()��car.brake()��car.stop()

Real Life Objects, Properties, and Methods

In real life, a car is an object.

A car has properties like weight and color, and methods like start and stop:

All cars have the same properties, but the property values differ from car to car.

All cars have the same methods, but the methods are performed at different times.

53 of 102

JavaScript Objects

You have already learned that JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to a variable named car:

<html>

<body>

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

<script>

var car = "Fiat";

document.getElementById("demo").innerHTML = car;

</script>

</body>

</html>

54 of 102

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Objects</h2>

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

<script>

// Create an object:

var car = {type:"Fiat", model:"500", color:"white"};

// Display some data from the object:

document.getElementById("demo").innerHTML = "The car type is " + car.type;

</script>

</body>

</html>

The car type is Fiat

The values are written as name:value pairs (name and value separated by a colon).

JavaScript objects are containers for named values called properties or methods.

55 of 102

Object Definition

You define (and create) a JavaScript object with an object literal:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Objects</h2>

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

<script>

// Create an object:

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

// Display some data from the object:

document.getElementById("demo").innerHTML =

person.firstName + " is " + person.age + " years old.";

</script>

</body>

</html>

John is 50 years old.

56 of 102

<html>

<body>

<h2>JavaScript Objects</h2>

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

<script>

// Create an object:

var person = {

firstName: "John",

lastName: "Doe",

age: 50,

eyeColor: "blue"

};

// Display some data from the object:

document.getElementById("demo").innerHTML =

person.firstName + " is " + person.age + " years old.";

</script>

</body>

</html>

JavaScript Objects

John is 50 years old.

57 of 102

Property

Property Value

firstName

John

lastName

Doe

age

50

eyeColor

blue

Object Properties

The name:values pairs in JavaScript objects are called properties:

Accessing Object Properties

You can access object properties in two ways:

objectName.propertyName

Or

objectName["propertyName"]

58 of 102

<html>

<body>

<p>You can use person.property or person["property"].</p>

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

<script>

// Create an object:

var person = {

firstName: "John",

lastName : "Doe",

id : 5566

};

// Display some data from the object:

document.getElementById("demo").innerHTML =

person["firstName"] + " " + person["lastName"];

</script>

</body>

</html>

You can use person.property or person["property"].

John Doe

59 of 102

Property

Property Value

firstName

John

lastName

Doe

age

50

eyeColor

blue

fullName

function() {return this.firstName + " " + this.lastName;}

Object Methods

Objects can also have methods.

Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions.

A method is a function stored as a property.

60 of 102

The this Keyword

In a function definition, this refers to the "owner" of the function.

In the example above, this is the person object that "owns" the fullName function.

In other words, this.firstName means the firstName property of this object.

var person = {  firstName: "John",  lastName : "Doe",  id       : 5566,  fullName : function() {    return this.firstName + " " + this.lastName;  }};

61 of 102

Example

name = person.fullName();

Try it Yourself »

If you access a method without the () parentheses, it will return the function definition:

Example

name = person.fullName;

Try it Yourself »

62 of 102

<html>

<body>

<p>An object method is a function definition, stored as a property value.</p>

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

<script>

// Create an object:

var person = {

firstName: "John",

lastName : "Doe",

id : 5566,

fullName : function() {

return this.firstName + " " + this.lastName;

}

};

// Display data from the object:

document.getElementById("demo").innerHTML = person.fullName();

</script>

</body>

</html>

63 of 102

<!DOCTYPE html>

<html>

<body>

<p>If you access an object method without (), it will return the function definition:</p>

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

<script>

// Create an object:

var person = {

firstName: "John",

lastName : "Doe",

id : 5566,

fullName : function() {

return this.firstName + " " + this.lastName;

}

};

// Display data from the object:

document.getElementById("demo").innerHTML = person.fullName;

</script>

</body>

</html>

64 of 102

JavaScript Strings

JavaScript strings are used for storing and manipulating text.

JavaScript Strings

A JavaScript string is zero or more characters written inside quotes.

var x = "John Doe";

String Length

To find the length of a string, use the built-in length property:

<body>

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

<script>

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

document.getElementById("demo").innerHTML = txt.length;

</script>

</body>

65 of 102

Finding a String in a String

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string

<html>

<body>

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

<script>

var str = "Please locate where locate occurs!";

var pos = str.indexOf("locate");

document.getElementById("demo").innerHTML = pos;

</script>

</body>

</html>

7

JavaScript counts positions from zero.0 is the first position in a string, 1 is the second, 2 is the third ...

66 of 102

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

<body>

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

<script>

var str = "Please locate where 'locate' occurs!";

var pos = str.lastIndexOf("locate");

document.getElementById("demo").innerHTML = pos;

</script>

</body>

21

Both indexOf(), and lastIndexOf() return -1 if the text is not found:

67 of 102

Both methods accept a second parameter as the starting position for the search:

<body>

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

<script>

var str = "Please locate where 'locate' occurs!";

var pos = str.indexOf("locate",15);

document.getElementById("demo").innerHTML = pos;

</script>

</body>

The indexOf() method accepts a second parameter as the starting position for the search

21

68 of 102

Searching for a String in a String

The search() method searches a string for a specified value and returns the position of the match:

<body>

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

<script>

var str = "Please locate where 'locate' occurs!";

var pos = str.search("locate");

document.getElementById("demo").innerHTML = pos;

</script>

</body>

7

69 of 102

Did You Notice?

The two methods, indexOf() and search(), are equal?

They accept the same arguments (parameters), and return the same value?

The two methods are NOT equal. These are the differences:

  • The search() method cannot take a second start position argument.
  • The indexOf() method cannot take powerful search values (regular expressions).

70 of 102

The slice() Method

slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: the start position, and the end position (end not included).

<body>

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

<script>

var str = "Apple, Banana, Kiwi";

var res = str.slice(7,13);

document.getElementById("demo").innerHTML = res;

</script>

</body>

Banana

71 of 102

<body>

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

<script>

var str = "Apple, Banana, Kiwi";

var res = str.slice(-12,-6);

document.getElementById("demo").innerHTML = res;

</script>

</body>

Banana

this example slices out a portion of a string from position -12 to position -6:

72 of 102

If you omit the second parameter, the method will slice out the rest of the string:

<html>

<body>

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

<script>

var str = "Apple, Banana, Kiwi";

var res = str.slice(7);

document.getElementById("demo").innerHTML = res;

</script>

</body>

</html>

Banana, Kiwi

73 of 102

Replacing String Content

The replace() method replaces a specified value with another value in a string:

<html>

<body>

<p>Replace "Microsoft" with “iicsindia.com" in the paragraph below:</p>

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

<p id="demo">Please visit Microsoft!</p>

<script>

function myFunction() {

var str = document.getElementById("demo").innerHTML;

var txt = str.replace("Microsoft",“iicsindia.com");

document.getElementById("demo").innerHTML = txt;

}

</script>

</body>

The replace() method does not change the string it is called on. It returns a new string.

By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not work:

74 of 102

To replace case insensitive, use a regular expression with an /i flag (insensitive):

str = "Please visit Microsoft!";var n = str.replace(/MICROSOFT/i, “iicsindia.com");

Note that regular expressions are written without quotes.

str = "Please visit Microsoft and Microsoft!";�var n = str.replace(/Microsoft/g, "W3Schools");

To replace all matches, use a regular expression with a /g flag (global match):

Replace all occurrences of "Microsoft" with "W3Schools" in the paragraph below:

75 of 102

75

Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():

<body>

<p>Convert string to upper case:</p>

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

<p id="demo">Hello World!</p>

<script>

function myFunction() {

var text = document.getElementById("demo").innerHTML;

document.getElementById("demo").innerHTML = text.toUpperCase();

}

</script>

</body>

76 of 102

76

<body>

<p>Convert string to lower case:</p>

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

<p id="demo">Hello World!</p>

<script>

function myFunction() {

var text = document.getElementById("demo").innerHTML;

document.getElementById("demo").innerHTML = text.toLowerCase();

}

</script>

</body>

A string is converted to lower case with toLowerCase():

77 of 102

77

The concat() Method

concat() joins two or more strings:

<html>

<body>

<h2>JavaScript String Methods</h2>

<p>The concat() method joins two or more strings:</p>

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

<script>

var text1 = "Hello";

var text2 = "World!";

var text3 = text1.concat(" ",text2);

document.getElementById("demo").innerHTML = text3;

</script>

</body>

</html>

78 of 102

78

<body>

<h2>JavaScript String.trim()</h2>

<p>Click the button to alert the string with removed whitespace.</p>

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

<script>

function myFunction() {

var str = " Hello World! ";

alert(str.trim());

}

</script>

</body>

The trim() method is not supported in Internet Explorer 8 and earlier versions

String.trim()

The trim() method removes whitespace from both sides of a string:

79 of 102

79

The charAt() Method

The charAt() method returns the character at a specified index (position) in a string

<body>

<h2>JavaScript String Methods</h2>

<p>The charAt() method returns the character at a given position in a string:</p>

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

<script>

var str = "HELLO WORLD";

document.getElementById("demo").innerHTML = str.charAt(0);

</script>

</body>

H

80 of 102

80

81 of 102

81

82 of 102

82

83 of 102

83

84 of 102

84

85 of 102

85

86 of 102

86

87 of 102

87

88 of 102

88

89 of 102

89

90 of 102

91 of 102

92 of 102

93 of 102

94 of 102

94

94

95 of 102

95

Place your screenshot here

96 of 102

96

Place your screenshot here

97 of 102

98 of 102

99 of 102

99

😉

100 of 102

100

101 of 102

101

102 of 102

Thanks!

Any questions?

You can find me at @username & user@mail.me

102