Ardhi UniversityLecture_3_part_b 2023
What is String?
JavaScript strings are for storing and manipulating text.
You can write by using single or double quotes.
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes
String Escape character
If you what to include special characters into string then use The backslash (\) escape character
Code Result What is inserted in a string
\' ' Single quote
\" " Double quote
\\ \ Backslash
let text = "We are the so-called \"Vikings\" from the north.";
Other list is
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator
\ Line continuation character or break line
String comparison
When using the == operator, x and y are equal.
When using the === operator, x and y are not equal.
String Methods
String length let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Ardhi UniversityLecture_3_part_b 2023
String slice() let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
NB: First index inclusive , last
index exclusive OR
let part = text.slice(7);
OR
let part = text.slice(-12);
String substring() let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
NB: No negative index is
supported like slice, all
negative index will be treated
as zero
String substr() let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
NB: The second parameter is
length to be extracted and not OR
index
let part = str.substr(7);
OR
let part = str.substr(-4);
String replace() let text = "Please visit Microsoft!";
let newText =
NB: By default, the replace() text.replace("Microsoft", "W3Schools");
method replaces only the first
match. OR what is output of below
NB: By default, the replace() let text = "Please visit Microsoft!";
method is case sensitive. let newText =
Writing MICROSOFT (with text.replace("MICROSOFT", "W3Schools");
upper-case) will not work.
String replaceAll() let text = "Please visit Microsoft!";
let newText = text.replaceAll("i", "A");
String toUpperCase() let text1 = "Hello World!";
let text2 = text1.toUpperCase();
Ardhi UniversityLecture_3_part_b 2023
String toLowerCase() let text1 = "Hello World!"; // String
let text2 = text1.toLowerCase(); // text2 is
text1 converted to lower
String concat() let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
OR you may use + operator
Let text3 = "Hello" + " " + "World!";
String trim() let text1 = " Hello World! ";
let text2 = text1.trim();
String trimStart() The trimStart() method works like trim(), but
removes whitespace only from the start of a string
String trimEnd() The trimEnd() method works like trim(), but
removes whitespace only from the end of a string.
String padStart() let text = "5";
let padded = text.padStart(4,"0");
String padEnd() let text = "5";
let padded = text.padStart(4,"x");
String charAt() let text = "HELLO WORLD";
let char = text.charAt(0);
String charCodeAt() let text = "HELLO WORLD";
let char = text.charCodeAt(0);
NB:
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).
Ardhi UniversityLecture_3_part_b 2023
String split() text.split(",") // Split on commas
text.split(" ") // Split on spaces
NB: If the separator is text.split("|") // Split on pipe
omitted, the returned
array will contain the
whole string in index
[0].
If the separator is "",
the returned array will
be an array of single
characters.
indexOf() let text = "Please locate where 'locate'
occurs!";
let index = text.indexOf("locate");
OR
let index = text.indexOf("locate",15);
lastIndexOf() let text = "Please locate where 'locate'
occurs!";
let index = text.lastIndexOf("locate");
OR
let index = text.indexOf("locate", 15);
search() let text = "Please locate where 'locate'
occurs!";
text.search("locate");
match() let text = "The rain in SPAIN stays mainly in
the plain";
text.match("ain");
matchAll() let text = "The rain in SPAIN stays mainly in
the plain";
text.matchAll("ain");
includes() let text = "Hello world, welcome to the
universe.";
text.includes("world");
Ardhi UniversityLecture_3_part_b 2023
startsWith() let text = "Hello world, welcome to the
universe.";
text.startsWith("world")
endsWith() let text = "Hello world, welcome to the
universe.";
text.endsWith("world", 11);
String template literals
Uses back-tick `` instead of quotes for a string and they are used for variable manipulations of a
string
The syntax is:
${...}
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`;
OR
let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
Array
An array is a special variable, which can hold more than one value.
const cars = ["Saab", "Volvo", "BMW"];
Syntax:
const array_name = [item1, item2, ...];
NB: Note the const is used as a common practice
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Ardhi UniversityLecture_3_part_b 2023
OR
const cars = new Array("Saab", "Volvo", "BMW");
NB: Do not use new Array approach if your element during declare and
initialization is one, will results into undefined
// Create an array with one element ???
const points = new Array(40);
A Common Error
const points = [40];
is not the same as:
const points = new Array(40);
Changing array
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Assign the whole array
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Array object or simply object (Array as object , in Python are called Dictionary)
Instead of using index to manipulated array items, they use key. The key or ID should be a string
pattern.
Array object uses {} while array uses [] and map uses ()
const person = {firstName:"John", lastName:"Doe", age:46};
Array Elements
Can be normal data type such as number
Can be an another array
Can be object(Dictionary in tem of python)
Can be function
Adding Array Elements
Ardhi UniversityLecture_3_part_b 2023
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
Looping Array Elements
Ardhi UniversityLecture_3_part_b 2023
Array method and properties
length const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;
Sort
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
OR for numbers
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
OR
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
For accuracy of number sorting use Fisher Yates shuffle
const points = [40, 100, 1, 5, 25, 10];
for (let i = points.length -1; i > 0; i--) {
let j = Math.floor(Math.random() * (i+1));
let k = points[i];
points[i] = points[j];
points[j] = k;
}
For Objects element in array such as
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
The sorting is done by compare properties
cars.sort(function(a, b){return a.year - b.year});
isArray() Array. isArray(person)
instanceof person instanceof Array
reverse() const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Math.min() const points = [40, 100, 1, 5, 25, 10];
Math.min.apply(null,points);
Math.max() const points = [40, 100, 1, 5, 25, 10];
Math.max.apply(null,points);
forEach() const numbers = [45, 4, 9, 16, 25];
Ardhi UniversityLecture_3_part_b 2023
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt += value + "<br>";
}
Note that the function takes 3 arguments:
The item value
The item index
The array itself
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value) {
txt += value + "<br>";
}
map() const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
return value * 2;
}
here numbers2 is also array
Or
const newArr = numbers1.flatMap((x) => x * 2);
filter() const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
every() const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
some() const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);
function myFunction(value, index, array) {
Ardhi UniversityLecture_3_part_b 2023
return value > 18;
}
indexOf() const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;
lastIndexOf() const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1;
findIndex() const numbers = [4, 9, 16, 25, 29];
let first = numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
Array.from() Array.from("ABCDEFG");
keys() const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keyscollection = fruits.keys();
To use keyscollection
Let text;
for (let x of keyscollection) {
text += x + "<br>";
}
then assign text to ularray.children[1].innerHTML or
ularray.children[1].textContent or
ularray.children[1].innerText
includes() const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // is true
Array Spread (…)
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];
const year = [...q1, ...q2, ...q3, ...q4];
Ardhi UniversityLecture_3_part_b 2023
Array const block scope
An array declared with const has Block Scope.An array declared in a block is not the same as an array
declared outside the block.
const cars = ["Saab", "Volvo", "BMW"];
// Here cars[0] is "Saab"
{
const cars = ["Toyota", "Volvo", "BMW"];
// Here cars[0] is "Toyota"
}
// Here cars[0] is "Saab"
But array with var has no block scope
var cars = ["Saab", "Volvo", "BMW"];
// Here cars[0] is "Saab"
{
var cars = ["Toyota", "Volvo", "BMW"];
// Here cars[0] is "Toyota"
}
// Here cars[0] is "Toyota"
Map
A Map holds key-value pairs where the keys can be any datatype while in object only string
A Map remembers the original insertion order of the keys.\
Create a Map
const fruits = new Map([
["apples", 500],
Ardhi UniversityLecture_3_part_b 2023
["bananas", 300],
["oranges", 200]
])
Add elements to a Map
// Create a Map
const fruits = new Map();
// Set Map Values
fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);
Replace Map element
fruits.set("apples", 200);
Get Map element
fruits.get("apples");
Delete Map Element
fruits.delete("apples");
Check if element is in Map
fruits.has("apples");
Check size of Map
Fruits.size()
NB: Object(Array Object) has no size function
Map Method
forEach() // Create a Map
const fruits = new Map();
// Set Map Values
fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);
// List all entries
Ardhi UniversityLecture_3_part_b 2023
let text = "";
fruits.forEach (function(value, key) {
text += key + ' = ' + value;
})
entries() // List all entries
let text = "";
for (const x of fruits.entries()) {
text += x;
}
Events
HTML events are "things" that happen to HTML elements. Here are some examples of HTML
events:
- An HTML web page has finished loading
- An HTML input field was changed
- An HTML button was clicked
Structure:
1. Writing in HTML
<element event listener ="some JavaScript">
<button onclick="displayDate()">The time is?</button>
2. Writing in Javascript
button.addEventListener("click", myFunction);
1. Writing in HTML. In the following example, an onclick event listener (with
code), is added to a <button> element:
Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The
time is?</button>
JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
Example
<button onclick="displayDate()">The time is?</button>
Here is a list of some common HTML events listener:
Ardhi UniversityLecture_3_part_b 2023
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
2. Witting in JS.
In JavaScript click is the event, myFunction is the event handler:
button.addEventListener("click", myFunction);
List of Event, Clck, change, keydown,keypress, load,input,select, play, waiting AND …
Class
Used to create class
The constructor here has name constructor instead of same class name as in JAVA
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
Using class to create objects
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
class Methods
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
Ardhi UniversityLecture_3_part_b 2023
method_3() { ... }
}
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
const date = new Date();
return date.getFullYear() - this.year;
}
}
const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
Class Inheritance
The keyword extends is used
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
Ardhi UniversityLecture_3_part_b 2023
let myCar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = myCar.show();
Creating getters and setters
class Car {
constructor(brand) {
this.carname = brand;
}
get cnam() {
return this.carname;
}
set cnam(x) {
this.carname = x;
}
}
const myCar = new Car("Ford");
document.getElementById("demo").innerHTML = myCar.cnam;
Class static method
Uses static keyword
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
const myCar = new Car("Ford");
// You can call 'hello()' on the Car Class:
document.getElementById("demo").innerHTML = Car.hello();
// But NOT on a Car Object:
// document.getElementById("demo").innerHTML = myCar.hello();
// this will raise an error.
Ardhi UniversityLecture_3_part_b 2023
JS DOM
Finding HTML Elements
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
Changing HTML Elements
Property Description
element.innerHTML = new html content Change the inner HTML of an
element
element.attribute = new value Change the attribute value of an
HTML element
element.style.property = new style Change the style of an HTML
element
Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream
Adding Events Handlers
document.getElementById(id).onclick = function(){code}