Number verification
function getPrecioMostrar(price) {
price = +price // just in case string: convert to nr
if (typeof price != "number" || isNaN(price)) {
return ("no es un formato correcto");
} else {
return (price.toFixed(2) + " €"); // fixed 2 decimals
}
}
console.log(getPrecioMostrar("4asd"))Math
function divide(a, b) {
return a / b;
}
console.log(divide(21,7)) // 3The substring() Method
substring() extracts a part of a string:
let text = "Hello world!";
let result = text.substring(1, 4); // result: ellThe toFixed() Method
toFixed() converts a number to a string, rounded to a specified number of decimals:
let num = 5.56789;
let n = num.toFixed(2);The split() Method
split() splits a string into an array of substrings, and returns the array:
let text = "How are you doing today?";
const myArray1 = text.split(" "); //How,are,you,doing,today?
const myArray2 = text.split(" ", 3); //How,are,youThe slice() method
slice() extracts a part of a string and returns the extracted part:
let text = "Hello world!";
let result = text.slice(0, 5); // Hello
let result = text.slice(3); // lo world!Capitalize a word
const Led = {
lampara1: "rojo",
lampara2: "verde",
lampara3: "azul"
}
const RGB = [
Led.lampara1.charAt(0).toUpperCase() + Led.lampara1.slice(1),
Led.lampara2.charAt(0).toUpperCase() + Led.lampara2.slice(1),
Led.lampara3.charAt(0).toUpperCase() + Led.lampara3.slice(1)
]ATM Function
const currencies = [500, 200, 100, 50, 20, 10, 5, 2, 1];
const maxCoin = 2;
function getFreshMoney(myMoney) {
for (let i = 0; i < currencies.length; i++) {
const currency = currencies[i];
if (myMoney >= currency) {
currency > maxCoin ? console.log(`|${currency}eur`) : console.log(`(${currency})eur`);
if (myMoney -= currency) {
if (myMoney >= currency) {
i--; // keeps in the same length in case there are more than 1 of a kind
}
}
}
}
}
const myMoney = 1498;
getFreshMoney(myMoney);Promt and string to number
function duplicaNumero() {
let num = prompt ('Please enter a number');
num = +num;
if (isNaN(num)) {
return ('Is this a number???');
}
return num *2;
}
console.log(duplicaNumero());
Leave a Reply