Replace All
- es2021에서 String.prototype.replaceAll() 이 추가될 예정이다.
var example = 'pot pot';
console.log(example.replace(/pot/, 'tom'));
console.log(example.replace(/pot/g, 'tom'));
var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1];
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
Convert string to number
the_string = '123';
console.log(+the_string);
the_string = 'hello';
console.log(+the_string);
Converting NodeList to Arrays
var elements = document.querySelectorAll('p');
var arrayElements = Array.from(elements);
Getting the last item in the array
var array = [1, 2, 3, 4, 5, 6];
console.log(array.slice(-1));
console.log(array.slice(-2));
console.log(array.slice(-3));
Shuffle elements from array
var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(
my_list.sort(function () {
return Math.random() - 0.5;
})
);
Flatten multidimensional array
var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);