0% found this document useful (0 votes)
27 views45 pages

JavaScript String and Number Methods

The document provides an overview of JavaScript string and number handling, including methods for string length, searching, extracting parts, replacing content, and converting case. It also covers number handling, including operations, NaN, Infinity, and methods for converting strings to numbers. Additionally, the document introduces arrays, their creation, accessing elements, and properties like length.

Uploaded by

bababhosdidas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views45 pages

JavaScript String and Number Methods

The document provides an overview of JavaScript string and number handling, including methods for string length, searching, extracting parts, replacing content, and converting case. It also covers number handling, including operations, NaN, Infinity, and methods for converting strings to numbers. Additionally, the document introduces arrays, their creation, accessing elements, and properties like length.

Uploaded by

bababhosdidas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

String Length

Strings are the text contents in JavaScript.


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

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


var sln = [Link]; //26
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:

Example
var str = "Please locate where 'locate' occurs!";
var pos = [Link]("locate"); //7

JavaScript counts positions from zero.


0 is the first position in a string, 1 is the second, 2 is the
third ...
The lastIndexOf() method returns the index of the
last occurrence of a specified text in a string:

Example
var str = "Please locate where 'locate' occurs!";
var pos = [Link]("locate"); //21

Both indexOf(), and lastIndexOf() return -1 if the text


is not found.
Searching for a String in a String
The search() method searches a string for a specified
value and returns the position of the match:

Example
var str = "Please locate where 'locate' occurs!";
var pos = [Link]("locate"); //7

The indexOf() method cannot take powerful search


values (regular expressions).
Extracting String Parts
There are 3 methods for extracting a part of
a string: <html><body>

slice(start, end) <h2>JavaScript String Methods</h2>


substring(start, end)
substr(start, length) <p>The slice() method extract a part of a string
and returns the extracted parts in a new
The slice() Method string:</p>
slice() extracts a part of a string and returns
the extracted part in a new string. <p id="demo"></p>
The method takes 2 parameters: the start <script>
position, and the end position (end not
included). var str = "Apple, Banana, Kiwi";
var res = [Link](7,13); //Banana
This example slices out a portion of a string [Link]("demo").innerHTML =
from position 7 to position 12 (13-1): res;
</script>
Example
var str = "Apple, Banana, Kiwi"; </body>
var res = [Link](7, 13); </html>
The substring() Method <!DOCTYPE html>
<html>
substring() is similar to slice(). <body>

<h2>JavaScript String Methods</h2>


The difference is that
<p>The substr() method extract a part of a
substring() cannot accept string
negative indexes. and returns the extracted parts in a new
string:</p>

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

var str = "Apple, Banana, <script>


Kiwi"; var str = "Apple, Banana, Kiwi";
var res = [Link](7,13); //Banana
var res = [Link](7, 13); [Link]("demo").innerHTML
= res;
</script>
If you omit the second
</body>
parameter, substring() will </html>
slice out the rest of the string.
The substr() Method <html>
substr() is similar to <body>
slice().
<h2>JavaScript String Methods</h2>

The difference is that the <p>The substr() method extract a part of a string
second parameter and returns the extracted parts in a new
string:</p>
specifies the length of
the extracted part. <p id="demo"></p>

<script>
Example var str = "Apple, Banana, Kiwi";
var str = "Apple, Banana, var res = [Link](7,6); //Banana
[Link]("demo").innerHTML =
Kiwi"; res;
var res = [Link](7, 6); </script>
The result of res will be: </body>
</html>
Banana
Replacing String Content
The replace() method replaces a specified value with another value in a string:

Example
str = "Please visit Microsoft!";
var n = [Link]("Microsoft", “TCS");

<html><body>

<h2>JavaScript String Methods</h2>

<p>Replace "Microsoft" with “TCS" in the paragraph below:</p>

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

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

<script>
function myFunction() {
var str = [Link]("demo").innerHTML;
var txt = [Link]("Microsoft",”TCS”);
[Link]("demo").innerHTML = txt;
}
</script></body></html>
Converting to Upper and Lower Case

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

Example
var text1 = "Hello World!"; // String
var text2 = [Link](); // text2 is text1 converted to upper

<html>
<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 = [Link]("demo").innerHTML;
[Link]("demo").innerHTML = [Link]();
}
</script>

</body>
</html>
A string is converted to lower case with toLowerCase():

Example
var text1 = "Hello World!"; // String
var text2 = [Link](); // text2 is text1 converted to lower

<html><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 = [Link]("demo").innerHTML;
[Link]("demo").innerHTML = [Link]();
}
</script>
</body></html>
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 = [Link](" ",text2);
Extracting String Characters
There are 3 methods for extracting string
characters:

• charAt(position)
• charCodeAt(position)

The charAt() Method


The charAt() method returns the character at a
specified index (position) in a string:
Example
var str = "HELLO WORLD";
[Link](0); // returns H

<html><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";
[Link]("demo").innerHTML =
[Link](0); //H

</script>
</body></html>
The charCodeAt() Method

The charCodeAt() method returns the unicode of the character at a specified index in a string:
The method returns a UTF-16 code (an integer between 0 and 65535).

Example
var str = "HELLO WORLD";

[Link](0); // returns 72

<html><body>

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

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

<script>
var str = "HELLO WORLD";
[Link]("demo").innerHTML = [Link](0);
</script>
</body></html>
JavaScript Numbers
JavaScript has only one type of number. Numbers can be written with or without
decimals.

<html><body>

<h2>JavaScript Numbers</h2>

<p>Numbers can be written with or without decimals:</p>

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

<script>
var x = 3.14;
var y = 3;
[Link]("demo").innerHTML = x + "<br>" + y;
</script>

</body></html>
var x = 10;
var y = 20;
var z = "The result is: " + x + y; //The result is: 1020

JavaScript will try to convert strings to numbers in all numeric operations:

This will work:


var x = "100";
var y = "10";
var z = x / y; // z will be 10

var x = "100";
var y = "10";
var z = x * y; // z will be 1000
var x = "100";
var y = "10";
var z = x - y; // z will be 90
var x = "100";
var y = "10";
var z = x + y; // z will not be 110 (It will be 10010)
NaN - Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal
number.

Trying to do arithmetic with a non-numeric string will result in NaN (Not a


Number):

<html><body>
<h2>JavaScript Numbers</h2>
<p>A number divided by a non-numeric string becomes NaN (Not a
Number):</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = 100 / "Apple";
</script>
</body></html>

var x = 100 / "Apple"; // x will be NaN (Not a Number)


var x = 100 / "10"; // x will be 10

You can use the global JavaScript function isNaN() to find out if a value is a number:

var x = 100 / "Apple";

isNaN(x); // returns true because x is Not a Number

If you use NaN in a mathematical operation, the result will also be NaN:

• var x = NaN;
var y = 5;
var z = x + y; // z will be NaN

Or the result might be a concatenation:

• Example
• var x = NaN;
• var y = "5";
• var z = x + y; // z will be NaN5
NaN is a number: typeof NaN returns number:

Example
typeof NaN; // returns "number“

Infinity (or -Infinity) is the value JavaScript will return if


you calculate a number outside the largest possible
number.

Example
var myNumber = 2;
while (myNumber != Infinity) { // Execute until Infinity
myNumber = myNumber * myNumber;
}
<html><body>

<h2>JavaScript Numbers</h2>

<p>Division by zero generates Infinity;</p>

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

<script>
var x = 2/0;
var y = -2/0;
[Link]("demo").innerHTML = x + "<br>" + y;
</script>

</body></html>

var x = 2 / 0; // x will be Infinity


var y = -2 / 0; // y will be –Infinity

Infinity is a number: typeof Infinity returns number.

typeof Infinity; // returns "number"


var x = 500;
var y = new Number(500);
// (x == y) is true because x and y have equal values
When using the === operator, equal numbers are not equal, because the
=== operator expects equality in both type and value.

Example
var x = 500;
var y = new Number(500);

// (x === y) is false because x and y have different types


Objects cannot be compared:

Example
var x = new Number(500);
var y = new Number(500);

// (x == y) is false because objects cannot be compared


Converting Variables to Numbers

There are 3 JavaScript methods that can be used to convert variables to


numbers:

The Number() method


The parseInt() method
The parseFloat() method

These methods are not number methods, but global JavaScript methods.
Global JavaScript Methods
• JavaScript global methods can be used on all JavaScript data types.
• These are the most relevant methods, when working with numbers:

Method Description
Number() Returns a number, converted from its argument.
parseFloat() Parses its argument and returns a floating point
number
parseInt() Parses its argument and returns an integer
The parseInt() Method
parseInt() parses a string and returns a whole number. Spaces are allowed. Only the
first number is returned:

Example
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN
If the number cannot be converted, NaN (Not a Number) is returned.

The parseFloat() Method


parseFloat() parses a string and returns a number. Spaces are allowed. Only the first
number is returned:
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
If the number cannot be converted, NaN (Not a Number) is returned.
JavaScript arrays
An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:

var car1 = "Saab";


var car2 = "Volvo";
var car3 = "BMW";

An array can hold many values under a single name, and you can access the
values by referring to an index number.

JavaScript arrays are used to store multiple values in a single variable.

var cars = ["Saab", "Volvo", "BMW"];


Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

var item = [item1, item2, ...];

Example
var cars = ["Saab", "Volvo", "BMW"];

Spaces and line breaks are not important. A declaration can span multiple lines:

Example

var cars = [
"Saab",
"Volvo",
"BMW"
];
Using the JavaScript Keyword new

The following example also creates an Array, and


assigns values to it:

Example
var cars = new Array("Saab", "Volvo", "BMW");

The two examples above do exactly the same. There is


no need to use new Array().

For simplicity, readability and execution speed, use the


first one (the array literal method).
Access the Elements of an
Array <html>
<body>
You access an array element
by referring to the index <h2>JavaScript Arrays</h2>
number. <p>JavaScript array elements are accessed using
numeric indexes (starting from 0).</p>

This statement accesses the <p id="demo"></p>


value of the first element in
<script>
cars: var cars = ["Saab", "Volvo", "BMW"];
[Link]("demo").innerHTML =
cars[0];
var name = cars[0]; </script>

</body>
</html>
Changing an Array <html>
<body>
Element
This statement changes <h2>JavaScript Arrays</h2>
the value of the first <p id="demo"></p>
element in cars:
<script>
var cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel"; [Link]("demo").innerHTML =
cars;
</script>
var cars = ["Saab", "Volvo",
</body>
"BMW"]; </html>
cars[0] = "Opel";
JavaScript Arrays
[Link] Saab,Volvo,BMW
("demo").innerHTML =
cars[0];
Arrays are Objects

Arrays are a special type of objects. The typeof


operator in JavaScript returns "object" for arrays.

Arrays use numbers to access its "elements". In this


example, person[0] returns John:

Array:
var person = ["John", "Doe", 46];
The length Property

The length property of an array returns the length of an array (the number
of array elements).

Example
<html><body>

<h2>JavaScript Arrays</h2>
<p>The length property returns the length of an array.</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("demo").innerHTML = [Link]; //4
</script>
</body></html>
Accessing the Last Array Element
Example
fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[[Link] - 1];

Looping Array Elements


The safest way to loop through an array, is using a for loop:

Example
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = [Link];

text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

• Banana
• Orange
• Apple
• Mango
<html><body>
<h2>JavaScript Arrays</h2>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>

<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = [Link];
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
[Link]("demo").innerHTML = text;
</script></body></html>

• Banana
• Orange
• Apple
• Mango
<html><body>
Adding Array <h2>JavaScript Arrays</h2>
Elements <p>The push method appends a new element
to an array.</p>
The easiest way to <button onclick="myFunction()">Try
add a new element to it</button>
<p id="demo"></p>
an array is using the <script>
push() method: var fruits = ["Banana", "Orange", "Apple",
"Mango"];
[Link]("demo").innerHTM
Example L = fruits;
function myFunction() {
var fruits = [Link]("Lemon");
["Banana", "Orange", //Banana,Orange,Apple,Mango,Lemon
[Link]("demo").innerHTM
"Apple", "Mango"]; L = fruits;
[Link]("Lemon"); }
</script>
// adds a new </body></html>
element (Lemon) to
fruits
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>The length property provides an easy way to append new elements to an array
without using the push() method.</p>

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

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

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("demo").innerHTML = fruits;

function myFunction() {
fruits[[Link]] = "Lemon";
[Link]("demo").innerHTML = fruits;
}
</script>

</body>
</html>
Adding elements with high indexes can create
undefined "holes" in an array: JavaScript
Arrays
<html><body> Adding elements
<h2>JavaScript Arrays</h2> with high indexes
<p>Adding elements with high indexes can create undefined can create
"holes" in an array.</p> undefined "holes"
<p id="demo"></p> in an array.
<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; Banana
fLen = [Link]; Orange
text = ""; Apple
for (i = 0; i < fLen; i++) { Mango
text += fruits[i] + "<br>"; undefined
} undefined
[Link]("demo").innerHTML = text; Lemon
</script>

</body></html>
[Link](): JavaScript Arrays
isArray returns true when used on an array:
<html> true
<body>

<h2>JavaScript Arrays</h2>

<p>The new ECMASCRIPT 5 method isArray


returns true when used on an array:</p>

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

<script>
var fruits = ["Banana", "Orange", "Apple",
"Mango"];
[Link]("demo").innerH
TML = [Link](fruits);
</script>

</body>
</html>
The join() method also joins all
Converting Arrays to array elements into a string.
Strings It behaves just like toString(), but in
The JavaScript method toString() addition you can specify the
converts an array to a string of separator:
(comma separated) array values. Example
var fruits =
Example ["Banana", "Orange", "Apple", "Ma
var fruits = ["Banana", "Orange", ngo"];
"Apple", "Mango"];
[Link]("dem [Link]("demo"
o").innerHTML = [Link](); ).innerHTML = [Link](" * ");
Result:
Banana,Orange,Apple,M Banana * Orange * Apple * Mango
ango
Popping Pushing
The pop() method removes the The push() method adds a new element to an
last element from an array: array (at the end):

Example
Example var fruits = ["Banana", "Orange", "Apple",
var fruits = ["Banana", "Orange", "Mango"];
"Apple", "Mango"]; [Link]("Kiwi");
[Link](); // Adds a new element ("Kiwi") to fruits

The push() method returns the new array


// Removes the last element length:
("Mango") from fruits
Example
The pop() method returns the var fruits = ["Banana", "Orange", "Apple",
value that was "popped out": "Mango"];
var x = [Link]("Kiwi");
// the value of x is 5
Example
var fruits = ["Banana", "Orange",
"Apple", "Mango"];
var x = [Link]();
// the value of x is "Mango"
Shifting Elements The unshift() method adds a new element to
Shifting is equivalent to popping, working an array (at the beginning), and "unshifts"
on the first element instead of the last. older elements:
The shift() method removes the first array Example
element and "shifts" all other elements to
a lower index. var fruits = ["Banana", "Orange", "Apple",
"Mango"];
Example [Link]("Lemon");
var fruits = ["Banana", "Orange", "Apple", // Adds a new element "Lemon" to fruits
"Mango"];
[Link](); The unshift() method returns the new array
// Removes the first element "Banana" length.
from fruits
Example
The shift() method returns the string that var fruits = ["Banana", "Orange", "Apple",
was "shifted out": "Mango"];
[Link]("Lemon"); // Returns 5
Example
var fruits = ["Banana", "Orange", "Apple",
"Mango"];
var x = [Link]();
// the value of x is "Banana"
Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator
delete:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined

Using delete may leave undefined holes in the array. Use pop() or shift() instead.

Splicing an Array
The splice() method can be used to add new items to an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](2, 0, "Lemon", "Kiwi");
JavaScript Array Methods splice()

The splice() method adds new elements to an array.

var fruits = ["Banana", "Orange", "Apple", "Mango"];


[Link](2, 0, "Lemon", "Kiwi");

The first parameter (2) defines the position where new elements should be added (spliced in).

The second parameter (0) defines how many elements should be removed.

The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

Original Array:
Banana,Orange,Apple,Mango

New Array:
Banana,Orange,Lemon,Kiwi,Apple,Mango

The splice() method returns an array with the deleted items:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](2, 2, "Lemon", "Kiwi");

//Banana,Orange,Lemon,Kiwi
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without
leaving "holes" in the array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](0, 1);

// Removes the first element of fruits


• The first parameter (0) defines the position where new elements should
be added (spliced in).
• The second parameter (1) defines how many elements should be removed.
• The rest of the parameters are omitted.
• No new elements will be added.
Merging (Concatenating) Arrays
The concat() method creates a new array by
merging (concatenating) existing arrays:

Example (Merging Two Arrays)


var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = [Link](myBoys); //Cecilie,Lone,Emil,Tobias,Linus

// Concatenates (joins) myGirls and myBoys


The concat() method does not change the existing
arrays. It always returns a new array.

The concat() method can take any number of array


arguments:

Example (Merging Three Arrays)


var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = [Link](arr2, arr3);
//Cecilie,Lone,Emil,Tobias,Linus,Robin,Morgan

// Concatenates arr1 with arr2 and arr3


Reversing an Array
The reverse() method reverses the elements in an array.

You can use it to sort an array in descending order:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](); // First sort the elements of fruits
[Link](); // Then reverse the order of the element

// Orange,Mango,Banana,Apple

You might also like