Today I will introduce some common techniques in Javascript to help you solve problems. Common problems in the process of setting up faster and easier.
1) Javascript Reverse String
const stringReverse = str => str.split("").reverse().join("");
stringReverse('hello world'); /*dlrow olleh*/
2) Scroll To Top Of Page
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();
3) Remove Duplicates In Array
const removeDuplicate = (arr) => [...new Set(arr)];
removeDuplicate([1, 2, 3, 4, 4, 2, 1]); // [1, 2, 3, 4]
4) Get Random Item In Array
const randomItemArray = (arr) => arr[Math.floor(Math.random() * arr.length)];
randomItemArray(['a', 'b', 'c', 1, 2, 3]);
5) Get Max Number in Array
const maxNumber = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
maxNumber([4,9,5,7,2]) /* 9 */
6) Check Type Number
function isNumber(num) {
return !isNaN(parseFloat(num)) && isFinite(num);
}
isNumber("Hello"); /*false*/
isNumber(123);/*true*/
7) Check Type Null
const checkNull = val => val === undefined || val === null;
checkNull(123) /* false */
checkNull() /* true */
checkNull('hello') /* false */
8) Get Min Number in Array
const minNumber = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
console.log(minNumber([3,5,9,7,1])) /*1*
9) Get Min Number in Array
const averageNumber = arr => arr.reduce((a, b) => a + b) / arr.length;
averageNumber([1, 2, 3, 4, 5]) /* 3 */
10) Checking the Element's Type
const checkType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
checkType(true) /*boolean*/
checkType("hello World") /*string*/
checkType(123) /*number*/
11) Count Element Occurrences in Array
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1,2,2,4,5,6,2], 2) /* Number 2 Occurrences 3 times in array */
12) Get Current URL Using Javascript
const getCurrentURL = () => window.location.href;
getCurrentURL() /* https://en.niemvuilaptrinh.com */
13) Capitalize Letters in Strings
const capitalizeString = str => str.replace(/b[a-z]/g, char => char.toUpperCase());
capitalizeString('niem vui lap trinh'); /* 'Niem Vui Lap Trinh' */
14) Convert RGB To Hex
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(52, 45, 125); /* Result: '#342d7d'*/
15)Convert Number to Array
const numberToArray = n => [...`${n}`].map(i => parseInt(i));
numberToArray(246) /*[2, 4, 6]*/
numberToArray(357911) /*[3, 5, 7, 9, 1, 1]*/
16)Get Content From HTML
This will be very useful for preventing users from being able to embed HTML tags in the web page when filling out information in the form of login, registration, post content..
And below is the code:
const getTextInHTML = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
getTextInHTML('<h2>Hello World</h2>'); /*'Hello World'*/
17)Assign Multiple Variables In JS
var [a,b,c,d] = [1, 2, 'Hello', false];
console.log(a,b,c,d) /* 1 2 'Hello' false */
18)Empty Array
let arr = [1, 2, 3, 4, 5];
arr.length = 0;
console.log(arr); /* Result : [] */
19)Copy Object In JS
const obj = {
name: "niem vui lap trinh",
age: 12
};
const copyObject = { ...obj };
console.log(copyObject); /* {name: 'niem vui lap trinh', age: 12}*/
20)Check Even and Odd Numbers
const isEven = num => num % 2 === 0;
console.log(isEven(1)); /*false*/
console.log(isEven(2)); /*true*/
21)Merge Two Or More Arrays JS
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr = arr1.concat(arr2);
console.log(arr); /* [1, 2, 3, 4, 5, 6] */
22)Copy Content To Clipboard
const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text)
}
23)Choose a Random Number From a Range of Values
var max = 10;
var min = 1;
var numRandom = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(numRandom)
24)Check Element Is Focused Or Not
const elementFocus = (el) => (el === document.activeElement);
elementIsInFocus(element);
/*if true element is focus*/
/*if false element is not focus*/
25)Testing Apple Devices With JS
const isAppleDevice =
/Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
/*if true element is apple devices **/
/*if false element is not apple devices*/
26)Convert String to Array
const str = "Hello";
const arr = [...str];
console.log(arr); /* ['H', 'e', 'l', 'l', 'o'] */
27)Using Arrow Functions in JS
/* regular function*/
const sum = function(x, y) {
return x + y;
};
/* arrow function */
const sum = (x, y) => x + y;
Summary:
I hope this article will provide you with useful javascript knowledge for development website and if you have any questions, please email me and I will respond as soon as possible. We hope you continue to support us Website so I can write more good articles. Have a nice day!
Top comments (1)
Good job , Thanks๐.