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
Operating System
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
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
Youtube
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); }
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);