Arrays
// gets elements of array based on conditions:
let words = ['one', 'two', 'three', 'four', 'five', 'six'];
let result = words.filter(word => word.length > 3); // ["three", "four", "five"]
// copy an array:
let words2 = words.slice();
// remove item from end/front:
var last = words.pop();
var first = words.shift();
// turn an Array-like object into an Array
let realArray = Array.apply(null, myArrayLikeObject);
Dates
new Date(); // Thu Dec 14 2023 12:34:56 GMT-0500 (EST)
new Date(new Date()); // Thu Dec 14 2023 12:34:56 GMT-0500 (EST)
new Date('12/14/2023'); // Thu Dec 14 2023 00:00:00 GMT-0500 (EST)
new Date(2023, 11, 14); // Thu Dec 14 2023 00:00:00 GMT-0500 (EST)
new Date(2023, 11, 14, 12, 34, 56, 789); // Thu Dec 14 2023 12:34:56 GMT-0500 (EST)
new Date('2023-12-14'); // Wed Dec 13 2023 19:00:00 GMT-0500 (EST)
new Date('2023-12-14T12:34:56'); // Thu Dec 14 2023 12:34:56 GMT-0500 (EST)
new Date('2023-12-14T12:34:56-0500'); // Thu Dec 14 2023 12:34:56 GMT-0500 (EST)
new Date('2023-12-14T12:34:56-0000'); // Thu Dec 14 2023 07:34:56 GMT-0500 (EST)
new Date(1702575296789); // Thu Dec 14 2023 12:34:56 GMT-0500 (EST)
new Date(2023, 11, 14, 12, 34, 56, 789).getTime(); // 1702575296789
Navigation
// reload page:
location.reload();
// navigate to URL:
window.location = 'https://joshwithee.com/blog';
// Scroll to top of page:
$('html,body').scrollTop(0);
Regex
// regex-replace-all:
var cleanedString = myString.replace(/\s+/g, ' ');
// check if string contains a pattern:
console.log(/p{2,}/.test("hippopotamus")); // true
// beware - using test() with the global flag will advance the lastIndex of the regex (even when passing different strings in):
var regex = /po/g;
// regex.lastIndex is at 0
regex.test("hippopotamus"); // true
// regex.lastIndex is now at 5
regex.test("hippopotamus"); // true
// regex.lastIndex is now at 7
regex.test("hippopotamus"); // false
// the exec() function returns an array
let regexResults =
/(^[^:]+):\/{2}([^:\/]+)(?::(\d+))?(.*)/.exec("https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL");
let [wholeMatch, protocol, domain, port, path] = regexResults;
console.log(wholeMatch); // https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL
console.log(protocol); // https
console.log(domain); // developer.mozilla.org
console.log(port); // undefined
console.log(path); // /en-US/docs/Learn/Common_questions/What_is_a_URL
Substrings
//Get index of last occurrence of substring:
var str = "Hello planet earth, you are a great planet.";
var n = str.lastIndexOf("planet"); //n=36 because there are 36 chars before last occurrence of "planet"
//Get a substring using start index (optional second param is end index):
var str = 'The morning is upon us.';
console.log(str.slice(-3)); // 'us.'
Element attributes
//Get index of last occurrence of substring:
var str = "Hello planet earth, you are a great planet.";
var n = str.lastIndexOf("planet"); //n=36 because there are 36 chars before last occurrence of "planet"
//Get JavaScript object from jQuery object:
var aJavaScriptObject = myjQueryObject[0]; // using array dereferencing operator
// (though this cannot use negative inputs like the get() method can)
var aJavaScriptObject = myjQueryObject.get(0); // retrieve one of the DOM elements matched by the jQuery object
// see: http://api.jquery.com/get/
Iterations
//Modify a property of each object in an array:
arrayOfObjects.map(function(obj){
obj["firstName"] = "John";
return obj;
});
Comparing values
// coalescing null or undefined:
let getUndefined = function(){};
let a = getUndefined();
let b = null;
let c = "Hey!";
let d = a || b || c; // d = "Hey!";
Debugging tricks
// substitute variables
// %s = string, %o = object, %i = integer, %f = float
console.log("My name is %s. I am not yet %i years old", "Josh", 100);
// get stack trace:
console.trace();
// hierarchical logging
console.group();
console.groupEnd();
// start and stop a timer
console.time();
console.timeEnd();
// check heap size
console.memory
// keep counts by string key
console.count("myCounter")
// clear console
console.clear();
// display objects as a table
let books = [{title:"Gone with the Wind", author:"Margaret Mitchell", published:1936}, {title:"War and Peace", author:"Leo Tolstoy", published:1869}, {title:"Pilgrim's Progress", author:"John Bunyan", published:1678}];
console.table(books);
// execute this in the console to set a breakpoint on a function:
debug(<function name>);
// use chrome dev tools to select an element, then reference it with $0 in the console
// apply CSS to colorize console logging:
console.log("%c" + myMessage, "background-color:lime;");
Global Variables
// check if global variable exists
if(window.myvariable){...}
// check if variable exists
if(typeof myvariable !== 'undefined'){...}
// add variable to global scope from anywhere
window.myvariable = ...;