JavaScript is a programming language that enables developers to create websites and web applications. It is a versatile language that can be used for a variety of purposes, such as creating dynamic user interfaces, processing data, and communicating with servers. Additionally, JavaScript is one of the most popular programming languages in use today, making it an excellent choice for web development.
Whether you love or hate JavaScript, there’s no denying that it’s one of the most popular programming languages in the world. In this post, we’ve collected a bunch of code snippets that will come in handy for any JavaScript developer.
From utility functions to work with dates and strings, these snippets should make your life a lot easier. And if you’re new to JavaScript, they might just help you get started with coding.
Table of Contents
Curated List of WordPress Code Snippets
Array & List
Convert an Array of JSON Objects to an Array of Objects —
var jsonArray = [ '{"name": "Edyth Hodkiewicz", "title": "Prof.", "age": 33,"phone": "1-636-405-1711 x0367", "email": "[email protected]" }', '{"name": "Nat Feeney", "title": "Mrs.", "age": 34, "phone": "(313) 679-9226 x25806", "email": "[email protected]" }', '{"name": "Raymond Friesen", "title": "Dr.", "age": 50, "phone": "881.612.1937 x915", "email": "[email protected]" }' ]; //use map() method var objectsArray = jsonArray.map(JSON.parse);
Operating System
Detect OS —
var userAgent = window.navigator.userAgent, platform = window.navigator?.userAgentData?.platform ?? window.navigator.platform, macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'], iosPlatforms = ['iPhone', 'iPad', 'iPod']; var platformDisplay = "Your OS is: "; if (iosPlatforms.indexOf(platform) !== -1) { platformDisplay += 'iOS'; } else if (/Android/.test(userAgent)) { platformDisplay += 'Android'; } else if (windowsPlatforms.indexOf(platform) !== -1) { platformDisplay += 'Windows'; } else if (macosPlatforms.indexOf(platform) !== -1) { platformDisplay += 'macOS'; } else if (!platform && /Linux/.test(platform)) { platformDisplay += 'Linux'; }
String
Remove Whitespace Characters —
var str = ' JavaScript strings are used to store and manipulate text. '; //remove both leading and trailing whitespace characters var newStr = str.trim(); //remove all white spaces var noBlankSpaceText = str.replaceAll(' ', ''); var noBlankSpaceText2 = str.replace(/ /g,''); var noBlankSpaceText3 = str.replaceAll(/\s/g,''); var noBlankSpaceText4 = str.replace(/\s+/, '') ;
Timer
Troubleshoot
Create Dynamic HTML Pages —
function changeText(){ document.querySelector('#content').textContent = 'New text added by button.'; } function addNewElements(){ const ul = document.createElement('ul'); const li1 = document.createElement('li'); li1.innerText = 'Item 1'; ul.appendChild(li1); const li2 = document.createElement('li'); li2.innerText = 'Item 2'; ul.appendChild(li2); document.querySelector('#content').appendChild(ul); } function loadNetworkData(){ fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(function(result) { //var objs = json.map(JSON.parse); const ul = document.createElement('ul'); for(var i = 0; i <= 10 ; i++){ let li = document.createElement('li'); li.innerText = result[i].title; ul.appendChild(li); } document.querySelector('#content').appendChild(ul); }); }
Youtube
Bulk Delete All Youtube’s Watch Later Videos —
setInterval(function() { document.querySelector('#contents button[aria-label="Action menu"]').click(); var things = document.evaluate('//span[contains(text(),"Watch later")]',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0; i < things.snapshotLength; i++) { things.snapshotItem(i).click(); } }, 1000);
Bulk “Add to Queue” Videos from a Youtube Playlist —
var itemIndex = 0; const maxToAdd = 10; const delay = 1000; //1 second if(itemIndex < maxToAdd){ setInterval(function() { document.querySelectorAll('#primary button[aria-label="Action menu"]')[itemIndex].click(); var items = document.evaluate('//yt-formatted-string[contains(text(),"Add to queue")]',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0; i < items.snapshotLength; i++) { items.snapshotItem(i).click(); } itemIndex++; }, delay); }