JS 2, String array methods, If and Switch statements, let and var properties, HTML forms and js validation and setInterval()/setTimeout()
We can use index and array methods on strings:
//We can use the index but can't edit a string like an array
"string"[2] //"r"
"string"[2] = "e" //"string"
//We can also use more specific methods
"string".charAt(2) //"r"
"string".charCodeAt //114
But arrays and strings are not of the same type:
typeof ["w","e","e","l"] //object
typeof "well" //string
We can convert each other using split(), toString() and join():
typeof "well".split("") == "w","e","e","l" //object
["w","e","e","l"].toString() //"w,e,e,l"
["w","e","e","l"].join("") //"well"
We use the Typeof operator and Array.isArray() to check the type of data:
Array.isArray("indeed".split(" ") ) //true
Array.isArray("indeed" ) //false
String data contains only 1 value and so is primitive, while Object contains more.
If and Switch
The IF statement executes a block of code if its condition is true:
//else_if for other conditions, _else_ if no condition is true
if(true){
return console.log("true")
}else if(){
}
else{
return console.log("false")
}
For multiple conditions we can use logical operators:
//We can't 3<x<10 so we have to repeat the variable
if ((x === 5 || y > 3 || x <= 10) && (loggedIn || userName === 'Steve')) {
//Run the code
}
if(x>3 && x<10){
//code here
}
We can also use switch and cases:
//We use break to close the case and default as the last case
switch (5) {
case true:
return console.log("number real")
break;
case false:
return console.log("number not")
break;
default:
return console.log("sdell")
}
//if more than one case shares the same code
const month = new Date().getMonth();
switch (month) {
case 0:
case 1:
case 2:
console.log("Winter"); // January, February, March
break;
case 3:
case 4:
case 5:
console.log("Spring"); // April, May, June
break;
...
default:
console.log("No month");
}
Strings, numbers, and objects can have falsy values, which will be false in boolean:
- 0
- '': Empty string
- null
- undefined
- NaN
//typeof null being an object is an old bug
typeof null + " " + typeof undefined //object, undefined
//null is a primitive value for "empty" variables
let vuoto = null
console.log( vuoto === null ) //true, assigned null value
//undefined is for the absence of a value, or non-existent keys in objects
let name;
console.log( name === undefined) //true, initialized not assigned variable
Ternary operator is a simplified conditional operator:
//The variable is used for returned values, works for if/else
let greeting = ( condition) ?
console.log("code returned for true")
:
console.log("code returned for false");
We can use the nullish coalescing operator for null/undefined values:
//using the ?? we get returned the right value if the left one is null/undefined
let amount = null;
let amount1 = 2
console.log(amount ?? 1) // 1
console.log(amount1 ?? 1) // 2
Text filter javascript and DOM exercise
Check this code implementing regex, forms, and setInterval:
Let, Var and differences
In 2015 the let keyword for variables was introduced:
//the main difference is in the scope of the variable
var z = 'hello';
var z = 'world'; //will allow to re-declare the variable
let j = 'hello';
let j = 'world'; //Syntax error on re-using the let keyword to re-assign
//Contrary to var global scope, let is limited to its block of code
let greeter = "hey hi";
let times = 5;
if (times > 3) {
var hello = "Say Hello JavaTpoint";
console.log(hello)
}
console.log(hello) //it shouldn't be declared, error when using let
//var can be called out of its block, which is prone to errors
The different scope can make the var accidentally change its value:
//here for example when calling the cb to see how the var=i changes in the for loop
//BUT being var global scoping it will change to 5 before the .push
var callbacks = [];
(function() {
var i;
for (i = 0; i < 5; i++) {
console.log("when does " + i + " change")
callbacks.push(
function() { return i; }
);
}
console.log("is this " + i)
})();
console.log(callbacks.map(
function(cb) { return cb(); } //resulting in [5, 5, 5, 5, 5]
)
);
//If we had let the for loop would have increased and pushed the [1,2,3,4,5] instead
Regex and string matching
We use Regular Expression Search Methods to search patterns in strings:
//text pattern between // and letters for modifiers
let pattern = /Lorem/i //i is for case insensitive
vipsum.search(pattern) //will return the index of the first match
vipsum.search(/loreM/i) //we can also put directly
To search more specific patterns with regex we can use:
//We get an array of the matched [letters] in the text
vipsum.match(/[qvgk]/g) //['g', 'q', 'g', 'q', 'g', 'v', 'v', 'q']
//First match between 2 values (if we use g then it's the same as [])
vipsum.match( /[q|x]/ ) // ['m', index: 4, input: 'Lorem ...']
//We can also check for whitespaces (\s includes newlines)/new lines (\n only lines)
vipsum.match( /\s/g ) //(62)[' ', ' ', ' ', ' ', ' ', ' ', '\n',...]
vipsum.match( /\n/g ) //(4)['\n', '\n', '\n', '\n']
//Match the string /s+/ case insensitive and on the global string
vipsum.match( /s+/ig ) //(10)['s', 's', 's', 'SSS', 's', 's', 's', 's', 's', 's']
We use the test() method to true/false if a pattern is present on the string, while exec() to return a pattern index match and input:
//The regex goes first [pattern].test/exec(html)
const primo= /lorem/i;
console.log( primo.test(html) ); //true
//input being the entire string is taken upon
let yull = /ipsum/gi.exec(html)
console.log(yull) //['ipsum', index: 6, input: 'Lorem ipsum ... ']
Then we have the .search() and .match() :
//.search() will return the index of the match if present
let visit = "Plant a tree!";
let n = visit.search(/plants/i);
console.log(n) //if no match then -1 return
//.match will return an array like exec.() but can contain multiple matches
console.log( "best is best".match(/best/g) ) //[best, best]
//Here we have html.search/match(___) when pattern is in ()
About variables used as new regex patterns:
//We can get a value from the input to then create a new RegExp
let oltre = document.getElementById("cosa").value
const regex = new RegExp( "(" + oltre + ")", 'ig'); // /regex/ig
const kok = html.innerHTML.split( regex );
About stricter filters:
//We can use renex on a split() method (for white spaces for example)
let spaced = html.innerHTML.split( /(\s)/ )
//while if we want to check if the input is only white spaces we do this
primo.match(/^\s*$/)
HTML forms and JS validation
We use forms to collect user input:
<Form> is a container for inputs/labels and the action attribute allows us to redirect the form after submission:
<form id="formula" method="post" action="https://www.ilpost.it/">
<label for="unon">First</label>
<input type="text" id="uno" name="unon"> <br>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="submit" value="submit">
</form>
For the check status and value of radio/checkbox buttons, we use the attributes .checked and value:

We use select to create a dropdown list.

To push JS content into HTML DOM we can use AppendChild() or innerHTML.
AppendChild() will record and update its content while innerHTML will reset it.
<input type="text" name="name" id="txt_name" >
<button onclick="kek()">
ADD
</button>
<p id="demo"></p>
<p id="demani"></p>
//To push/append an element it needs to be createTextNode()
function kek(){
let inside = document.getElementById("txt_name").value
let textnode = document.createTextNode(inside+ " ");
document.getElementById("demo").appendChild(textnode); //will show past inputs
let text;
if (isNaN(inside) || inside < 1 || inside > 10) {
text = "Input not valid";
} else {
text = inside + " I guess";
}
document.getElementById("demani").innerHTML = text; //only current text value
}
We can replace() an innerHTML element using regex.
let ipsum = document.getElementById("lorem")
let gulp = ipsum.innerHTML.replace(/MagNi/gi, "Picoolo")
ipsum.innerHTML = `<span >` + gulp + `</span>`
Setinterval() and SetTimeout()
The setInterval() method calls a function at specified millisecond intervals, it returns an ID that can be used to stop it using clearInterval():
<button class="btn btn-success" onclick="real()">Orario</button>
<button class="btn btn-secondary" onclick="stopped()">ferma</button>
<h3 id="attuale"></h3>
We setInterval() using the new Date() object (that updates itself) to create a clock:
let attuale = document.getElementById("attuale")
let att;
//we create the variable for the setInterval() ID and use it to stop it
function current(){
const date = new Date();
attuale.innerHTML = date.toLocaleTimeString();
}
function real(){
att= setInterval(() => {
current()
}, 1000);
}
function stopped(){
clearInterval(att)
}

The setTimeout() method calls a function once after a number of milliseconds:
To repeat a setTimeout() function :
<h2 id="stime" class="text-center"></h2>
//we need to put the setTimeout() in its own function
//and can be stopped with clearTimeout()
let stime= document.getElementById("stime")
function blue(){
let arti= new Date()
stime.innerHTML= arti.toLocaleTimeString();
setTimeout( blue, 1000 )
}
blue()

Last updated
Was this helpful?