We can use JavaScript to remove a substring from a string by using the JavaScript String replace() method. text.replace("some_substring", ""); Let’s see an example of this below. Let’s use the code above on a string and see the results. var somestring = "After running the replace method this is the text we want to remove, […]
JavaScript
Using JavaScript to Convert Month Number to Name
We can use JavaScript to convert a month number to a name easily by making use of an array of month names. To convert a month number to a name, we simply have to create an array of month names, which we will call months. We will then match the given month number to the […]
Remove Commas From Array in JavaScript
We can mean two things when we say that we want to remove commas from an array in JavaScript. The first is to actually remove commas that are found in an array. The second thing we can mean by this is to display the values of an array without them being separated by commas. Let’s […]
Using JavaScript to Return String
In JavaScript, to return a string in a function, we simply need to use the return statement. Here is a very simple example. function someFunction(){ return "someString"; }; If we were to call the function, someFunction(), then the string "someString" would be returned. function someFunction(){ return "someString"; }; console.log(someFunction()); #Output someString The return statement will […]
How to Change an Image on Hover Using JavaScript
We can change an image on hover in JavaScript by making use of the image src property along with the onmouseover and onmouseout events. <img src="img.jpg" onmouseover="changeImg1()" onmouseout="changeImg2()"> <script> function changeImg1(){ //Swap image to the new one }; function changeImg2(){ //Swap image back }; </script> Let’s see the full HTML code and JavaScript for this […]
Using JavaScript to Square a Number
There are a bunch of ways we can use JavaScript to square a number. The first method we will go over is using the JavaScript exponentiation operator, **. var squaredNumber = 6**2; console.log(squaredNumber); #Output 36 The exponentiation operator will simply take the first number, and raise it to the power of the second number. So […]
JavaScript toFixed – How to Convert a Number to a String
The JavaScript toFixed method will take a number and convert it to a string. You can also pass the toFixed() method a number and it will round the number to that many decimal places. If no number is given, it will just round the number to an Integer. var num = 10.7354; var numToString = […]
Using JavaScript to Convert Double to Integer
We can use JavaScript to convert a double to an integer by using the JavaScript parseInt() method. var num = parseInt(20.12345); The above code would return the number 20. The parseInt() JavaScript method will parse the value given to it and then return the Integer value. If no integer is found at the start, NaN […]
How to Check if a String Contains Vowels in JavaScript
We can easily check if a string contains vowels in JavaScript by either using a for loop to check each character individually to see if it is a vowel or not, or we can use the JavaScript match() method. Let’s take a look at both methods below. We will start with using a for loop. […]
Using JavaScript to Check If String Contains Only Certain Characters
We can use JavaScript to check if a string contains only certain characters by using nested for loops to check individually if each character is one of those characters or not. function containsCertainCharacters(theString, chars){ for( var i=0; i<theString.length; i++ ){ for( var k=0; k<chars.length; k++ ){ if(theString.charAt(i) === chars.charAt(k)){ return true; } } } return […]
for each char in string – How to Loop Over Characters of String in JavaScript
To loop over the characters of a string in JavaScript, we can use a for loop, the JavaScript charAt() method, and the length property to loop over each character in the following way. var example_string = "example"; for( var i=0; i<example_string.length; i++ ){ console.log(example_string.charAt(i)); } #Output: e x a m p l e When working […]
Using JavaScript to Convert String to Boolean
We can use JavaScript to convert a string variable to a boolean value by using the JavaScript Boolean() function. Non-empty strings are converted to true and empty strings are converted to false. var some_string = "This is a string"; var empty_string = ""; console.log(Boolean(some_string)); console.log(Boolean(empty_string)); #Output: true false If you just want to check if […]
Using JavaScript to Return Two Values
In JavaScript, the easiest way to return two values is to store them in an array and return the array containing the two values. function returnTwoValues(){ var arrayToReturn = [2,3]; return arrayToReturn; }; In the code above, we wanted to return the two values 2 and 3, so we create a new array, arrayToReturn, and […]
Using JavaScript to Insert Item Into Array
We can use JavaScript to insert an item into an array by using the JavaScript Array splice() method. We will need to pass the index and an object to the splice() method to insert an object at a certain position. var numArray = [0, 1, 2, 4]; numArray.splice(3, 0, 3); console.log(numArray); #Output: [0, 1, 2, […]
Using JavaScript to Add to Array
In JavaScript, to add to an array, we can simply use the JavaScript Array push() method. The push() method will add an element to the end of the array. var numArray = [1, 2, 3]; numArray.push(4); console.log(numArray); #Output: [1, 2, 3, 4] You can also use the push() method to add multiple elements to an […]
Using JavaScript to Check if Array is Empty
We can easily use JavaScript to check if an array is empty. An empty array has length 0, and is equal to False, so to check if an array is empty, we can just check one of these conditions. var emptyArray = []; #length check if ( emptyArray.length == 0){ console.log("Array is empty!"); } #if […]
Using JavaScript to Create an Empty Array
We can use JavaScript to create an empty array easily by initializing the array to no items with open and closed square brackets. var emptyArray = []; In JavaScript, arrays are a collection of objects which are ordered. When working with arrays, it can be useful to be able to easily create an empty array, […]
Using JavaScript to Convert Float to Integer
We can use JavaScript to convert a float to an integer by using the JavaScript parseInt() method. var num = parseInt(20.12345); The above code would return the number 20. The parseInt() JavaScript method will parse the value given varaible to it and then return the Integer value. If no integer is found at the start, […]
Using JavaScript to Get the Length of Array
We can use JavaScript to get the length of an array easily by simply using the JavaScript Array length property. arr.length And here is a simple example. var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(numbers.length); #Output 9 When working with arrays, it can be useful to be able to easily […]
Using JavaScript to Calculate Average of Array of Numbers
To get the average of an array in JavaScript, we can use the JavaScript Array reduce() method along with the length property. Here is the setup for how this can be done: var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; function sumArray(total, item) { return total + item; } var averageOfNumbers […]
Subtract All Numbers in an Array Using JavaScript
To subtract all of the numbers of an array in JavaScript, we can use the JavaScript Array reduce() method. Here is the setup for how this can be done: var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; function subtractArray(total, item) { return total – item; } console.log(numbers.reduce(subtractArray)); #Output -43 We can […]
Get the Sum of Array in JavaScript
To get the sum of an array in JavaScript, we can use the JavaScript Array reduce() method. Here is the setup for how this can be done: var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; function sumArray(total, item) { return total + item; } console.log(numbers.reduce(sumArray)); #Output 45 We can shorten our […]
Using JavaScript to Create a Unique Array
We can use JavaScript to create a unique Array by converting the array to a set with the new Set() method and then back to an array with the Array.from() method. var numbersArray = [0,7,7,7,0,2,3,1,1,4,5,6,7]; var convertToSet = new Set(numbersArray); var convertBackToArray = Array.from(convertToSet); console.log(convertBackToArray); #Output: [0, 7, 2, 3, 1, 4, 5, 6] Look […]
Convert String to Array in JavaScript
To convert a string to an array using JavaScript, the easiest way is with the JavaScript Array.from() method. var someString = "string"; var stringToArray = Array.from(someString); console.log(stringToArray); #Output: ["s", "t", "r", "i", "n", "g"] If we want to convert a string into an array of elements with a delimiter, we can use the split() method […]
Using JavaScript to Add Items to Set
In JavaScript, to add to a set, you can use the add() method. add() will add an element to the set if the element is not already in the set. var numbersSet = new Set([1, 2, 3]); numbersSet.add(4); console.log(numbersSet); #Output: {1, 2, 3, 4} You can also use the Spread Operator (…) to add multiple […]
Using JavaScript to Remove Duplicates From Array
We can use JavaScript to remove duplicates from an array by converting the array to a set with the new Set() method and then back to an array with the Array.from() method. var numbersArray = [0,7,7,7,0,2,3,1,1,4,5,6,7]; var convertToSet = new Set(numbersArray); var convertBackToArray = Array.from(convertToSet); console.log(convertBackToArray); #Output: [0, 7, 2, 3, 1, 4, 5, 6] […]
Using JavaScript to Replace Character in String
We can use JavaScript to replace a character in a string by using the JavaScript String replace() method. text.replace(/i/g, 'e'); Let’s say we have the following HTML: <div id="div1"> <p id="p1">We will update the text: <span id="span1">text_with_underscores</span></p> </div> If we want to change the underscore characters in the span “text_with_underscores” and replace them with spaces, […]
Convert String to Float in JavaScript
We can convert a string to float in JavaScript by using the JavaScript parseFloat() method. var num = parseFloat("20.12345"); The above code would return the number 20.12345. The parseFloat() JavaScript method will parse the value given to it as a string and then return the first Float in the string. If no number is found […]
Using JavaScript to Convert String to Integer
We can use JavaScript to convert a string to an integer by using the JavaScript parseInt() method. var num = parseInt("20.12345"); The above code would return the number 20. The parseInt() JavaScript method will parse the value given to it as a string and then return the first Integer in the string. If no integer […]
Using JavaScript to Check if String Contains Letters
There are many ways we can use JavaScript to check if a string contains a letter. We will go over two simple methods below to do this. The first uses the JavaScript test() method and a regex expression. /[a-zA-Z]/.test(someString); The regex expression /[a-zA-Z]/ will check for any letter, lowercase or uppercase. The test() method will […]
Using JavaScript to Check if String Contains Only Letters
We can use JavaScript to check if a string contains only letters. One of the simplest ways to do this is to use the JavaScript test() method and a regex expression. /^[a-zA-Z]+$/.test(someString); The regex expression [a-zA-Z] will check for any letter lowercase or upper. The rest of the regex expression checks that every character in […]
Using JavaScript to Check if String Contains Only Numbers
We can use JavaScript to check if a string contains only numbers. One of the simplest ways to do this is to use the JavaScript test() method and a regex expression. /^\d+$/.test(someString); The regex expression \d will check for any number from 0-9. The rest of the regex expression checks that every character in the […]
Using JavaScript to Check if String Contains Numbers
There are many ways we can use JavaScript to check if a string contains numbers. We will go over two simple methods below to do this. The first uses the JavaScript test() method and a regex expression. /\d/.test(someString); The regex expression /\d/ will check for any number from 0-9. The test() method will check the […]
Remove String From Array in JavaScript
To remove a string from an array in JavaScript, the easiest way is to use the JavaScript Array filter() method. Below shows an example of how you could remove the string “hello” from an array of strings with filter() method. var array_of_strings = ["hello","goodbye","Hello","hey","hi"]; var filtered_array = array_of_strings.filter(x => x != "hello"); console.log(filtered_array); // Output: […]
Creating a JavaScript Function to Divide Two Numbers
We can use JavaScript to create a function that will divide two numbers easily. We simply need to use the division operator / in our function. Here is the simple function to divide two numbers. function divideTwoNumbers(number1,number2){ return number1/number2; }; And that’s it. Our simple function called divideTwoNumbers takes two parameters, the two numbers you […]
Creating a JavaScript Function to Subtract Two Numbers
We can use JavaScript to create a function that will subtract two numbers easily. We simply need to use the subtraction operator – in our function. Here is the simple function to subtract two numbers. function subtractTwoNumbers(number1,number2){ return number1-number2; }; And that’s it. Our simple function called subtractTwoNumbers takes two parameters, the two numbers you […]
Creating a JavaScript Function to Add Two Numbers
We can use JavaScript to create a function that will add two numbers easily. We simply need to use the addition operator + in our function. Here is the simple function to add two numbers. function addTwoNumbers(number1,number2){ return number1+number2; }; And that’s it. Our simple function called addTwoNumbers takes two parameters, the two numbers you […]
Creating a JavaScript Function to Multiply Two Numbers
We can use JavaScript to create a function that will multiply two numbers easily. We simply need to use the multiplication operator * in our function. Here is the simple function to multiply two numbers. function multiplyTwoNumbers(number1,number2){ return number1*number2; }; And that’s it. Our simple function called multiplyTwoNumbers takes two parameters, the two numbers you […]
JavaScript if else Shorthand Statement
In JavaScript, we can write an if else statement in shorthand by using the conditional (ternary) operator. (condition) ? option1:option2; So if the condition in the code above is true, then the first option will be executed. Otherwise, the second option will run if the condition is false. Let’s see some examples of this below. […]
JavaScript Random Color – How to Generate a Random Color In JavaScript
To generate a random color using JavaScript, the simplest way is to use the JavaScript random() method along with the Math.floor() and toString() methods. var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16)); We can wrap this code in a function so that we can reuse this function anytime we want a new random color. function randomColor(){ return […]
Using JavaScript to Get a Random Number Between 1 and 20
We can use JavaScript to get a random number between 1 and 20. To do this we first need to know how to generate a random number. To generate a random number using JavaScript, the simplest way is to use the JavaScript random() method: var random = Math.random(); The Javascript Math random() method generates a […]
Using JavaScript to Get a Random Number Between 1 and 100
We can use JavaScript to get a random number between 1 and 100. To do this we first need to know how to generate a random number. To generate a random number using JavaScript, the simplest way is to use the JavaScript random() method: var random = Math.random(); The Javascript Math random() method generates a […]
Using JavaScript to Get a Random Number Between 1 and 10
We can use JavaScript to get a random number between 1 and 10. To do this we first need to know how to generate a random number. To generate a random number using JavaScript, the simplest way is to use the JavaScript random() method: var random = Math.random(); The Javascript Math random() method generates a […]
Using JavaScript to Get a Random Number Between 1 and 5
We can use JavaScript to get a random number between 1 and 5. To do this we first need to know how to generate a random number. To generate a random number using JavaScript, the simplest way is to use the JavaScript random() method: var random = Math.random(); The Javascript Math random() method generates a […]
Using JavaScript to Redirect to a Relative URL
In JavaScript, we can redirect to a relative URL by using the window.location object and setting it to the relative path we want. window.location.href = "some-page.com"; Here are some quick relative redirect examples which we will go over below. window.location.href = "some-page.com"; //This redirect will be relative to our CURRENT directory window.location.href = "/some-page.com"; //This […]
setTimeout javascript – How the setTimeout() Method in JavaScript Works
The setTimeout() method in JavaScript will run a function or code after a set amount of milliseconds have passed. setTimeout(function(){ //Code that will run after 5000 milliseconds }, 5000); You can see in the code above that the setTimeout() method has the second parameter of 5000. This is how long (in milliseconds) the method will […]
cleartimeout JavaScript – How the clearTimeout() Method in JavaScript Works
The clearTimeout() method in JavaScript clears the timer which has been set by a setTimeout() method. var timer = setTimeout(function(){ //Code that will after 1000 milliseconds }, 1000); function clearTimer(){ clearTimeout(timer); } In the code above, the setTimeout() method will run the function after 1000 milliseconds(1 second). We can change that parameter to be however […]
Using JavaScript to Stop a Timer
The best way to use JavaScript to stop a timer we have created is by using the clearInterval() and clearTimeout() methods. The clearInterval() method in JavaScript clears the timer which has been set by a setInterval() method. var interval = setInterval(function(){ //Code that will run every 1000 milliseconds if( //some condition ){ //This will stop […]
Using JavaScript to Round to 4 Decimal Places
In JavaScript, to round a number to 4 decimal places we can use the Math.round() method in the following JavaScript code: var roundedNumber = Math.round(num * 10000) / 10000; In the code above, num will be the number that we want to round to 4 decimal places. So if we want to round the number […]
Using JavaScript to Round to 3 Decimal Places
In JavaScript, to round a number to 3 decimal places we can use the Math.round() method in the following JavaScript code: var roundedNumber = Math.round(num * 1000) / 1000; In the code above, num will be the number that we want to round to 3 decimal places. So if we want to round the number […]
Using JavaScript to Get New Date Format in dd mm yy
We can use JavaScript to get a new date in the format of dd mm yy by making use of the JavaScript toLocaleString() method. There are many configurations we can utilize with the toLocaleString() method to display the date how we want. One of these configurations will get the format we want. Note that we […]
Using JavaScript to Get Date Format in yyyy-mm-dd hh mm ss
We can use JavaScript to get the date in the format of yyyy-mm-dd hh mm ss by making use of the JavaScript toLocaleString() method. There are many configurations we can utilize with the toLocaleString() method to display the date how we want. One of these configurations will get the format we want. Here is the […]
Using JavaScript to Get Date Format in dd mm yyyy
We can use JavaScript to get the date in the format of dd mm yyyy by making use of the JavaScript toLocaleString() method. There are many configurations we can utilize with the toLocaleString() method to display the date how we want. One of these configurations will get the format we want. Note that we will […]
Using JavaScript to Format the Date in mm dd yyyy
We can use JavaScript to format the date in mm dd yyyy by making use of the JavaScript toLocaleString() method. There are many configurations we can utilize with the toLocaleString() method to display the date how we want. One of these configurations will get the format we want. Note that we will use the toLocaleDateString() […]
Using JavaScript to Get Date Format in yyyy mm dd
We can use JavaScript to get the date in the format of yyyy mm dd by making use of the JavaScript toLocaleString() method. There are many configurations we can utilize with the toLocaleString() method to display the date how we want. One of these configurations will get the format we want. Note that we will […]
Using Javascript to Check if Value is Not Undefined
We can easily use JavaScript to check if a value is not undefined by using the conditional operation not equal to, !=. Let’s see this below. if( value1 != undefined ){ //Value is not undefined } And here it is with a very simple example. var value1 = 1; if( value1 != undefined ){ console.log("value1 […]
Using Javascript to Check if Value is Not Null
We can easily use JavaScript to check if a value is not null by using the conditional operation not equal to, !=. Let’s see this below. if( value1 != null ){ //Value is not Null } And here it is with a very simple example. var value1 = 1; if( value1 != null ){ console.log("value1 […]
JavaScript If Not – Check if a Condition is False
We can use the JavaScript if not statement to check if a condition is not true. Usually in a JavaScript if-statement, we are looking to see if a certain condition is true. This can be useful in certain scenarios when we only want to know if a condition is false. Here is the simple code […]
Using JavaScript to Get Today’s Date
We can use JavaScript to get today’s date by making use of the JavaScript toLocaleString() method. There are many configurations we can utilize with the toLocaleString() method to display the date how we want. We will go over some of our favorites. The JavaScript toLocaleString method will take a date object and return the date […]
JavaScript Array includes Method
We can use the JavaScript Array includes() method to see if an item is contained in a given array. This is pretty straightforward. Here is the code below. someArray.includes(item)); The includes() method will return either true or false based on whether the item is found in the array. Let’s see a simple example of this […]
JavaScript String endsWith Method
Using the JavaScript String endsWith() method, we can check to see if a string ends with a certain character or string. The endsWith method is used on a string and takes a string as its parameter. someString.endsWith("anotherString"); Let’s take a look at an example of this below. Let’s say we have the following JavaScript: var […]
JavaScript String startsWith Method
Using the JavaScript String startsWith() method, we can check to see if a string starts with a certain character or string. The startsWith method is used on a string and takes a string as its parameter. someString.startsWith("anotherString"); Let’s take a look at an example of this below. Let’s say we have the following JavaScript: var […]
Reverse For Loop JavaScript
We can use a reverse for loop in JavaScript to loop through an array backwards. Let’s first take a look at a simple for loop to see it’s setup. for( var i=0; i<arrayOfNumbers.length; i++ ){ console.log(arrayOfNumbers[i]); }; This for loop will access the items at the start of an array first. So to do a […]
Using JavaScript to Remove an Element From the DOM
We can use JavaScript to remove an element from the DOM by simply using the remove() method. document.getElementById("div1").remove(); Let’s say we have the following html: <div id="div1">This is a div that will remain.</div> <div id="div2">This is a div that we can Remove with JavaScript.</div> <div id="div3">This is a div that will remain.</div> Next, we want […]
Find Common Elements in Two Arrays Using JavaScript
To find common elements in two arrays in JavaScript, we simply need to make use of the JavaScript Array filter() and includes() methods. Here is the code to get this done. var commonElementsArray = firstArray.filter(element => secondArray.includes(element)); Let’s add to this code and show an example to show how easy it is to find common […]
Push Multiple Items to Array in JavaScript
To push multiple items to an array in JavaScript we simply can use the JavaScript Array push() method with the items separated by a commas. someArray.push("d","e","f"); Let’s show this with a simple example. var someArray = ["a","b","c"]; someArray.push("d","e",true,1); console.log(someArray); #Output ['a', 'b', 'c', 'd', 'e', true, 1] Push Multiple Items to Array in JavaScript if […]
Using JavaScript to Count the Occurrences in a String
We can use JavaScript to count the occurrences of a char or number in a string by using the JavaScript match() method, the length property, and a regex expression. someString.match(/c/gi).length; Not that the formula above works great as long as the character or number is in the string. However, if it is not found in […]
Using JavaScript to Detect Window Resize
We can use JavaScript to detect a window resize by using the addEventListener() method on the window object. window.addEventListener("resize", function(event){ //Do something when the user resizes the window }); Let’s see a simple example of this below. Let’s say we have the following JavaScript code: window.addEventListener("resize", function(event){ alert("The window has been resized."); }); No matter […]
Using JavaScript to Reverse an Array
We can use JavaScript to reverse an array by simply using the JavaScript Array reverse() method. someArray.reverse(); Let’s see the reverse array in use with a simple example. var numbersArray = [1,2,3,4,5,6,7,8,9,10]; //Reverse the order of the array numbersArray.reverse(); console.log(numbersArray); #Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] Notice that using the […]
Uncheck a Radio Button Using JavaScript
We can uncheck a radio button using JavaScript by making use of the getElementById() method along with targeting the checked property value of an element. We simply need to change the checked property value of the radio button to false. Here is how we can do this: document.getElementById("radioButton").checked = false; Let’s see an example of […]
How to Uncheck All Checkboxes in JavaScript
To uncheck all checkboxes in JavaScript, the simplest way is to target the input elements and change their checked property to false. Let’s first go over how to set a checkbox input checked property to false using JavaScript. document.getElementById("checkboxInput").checked = false; There are many ways we can target an element, we used the getElementById() method […]
Set Checkbox as Checked in JavaScript
To set a checkbox as checked using JavaScript, the simplest way is to target the input element and change its checked property to true. document.getElementById("checkboxInput").checked = true; If we want to uncheck a checkbox using JavaScript, we can target the input element and change its checked property to false: document.getElementById("checkboxInput").checked = false; Let’s say we […]
Check if Checkbox is Checked in JavaScript
To check if a checkbox is checked in JavaScript, the simplest way is to target the checkbox using a method like getElementById() and then check the checked property of the element to see if it is true or false. document.getElementById("checkboxInput").checked We can then put this in an if-else statement. var isChecked = document.getElementById("checkboxInput").checked; if( isChecked […]
How to Select All Checkboxes in JavaScript
To select all checkboxes in JavaScript and set them to checked, the simplest way is to target the input elements and change their checked property to true. Let’s first go over how to set a checkbox input checked property to true using JavaScript. document.getElementById("checkboxInput").checked = true; There are many ways we can target an element, […]
Convert a Set to Array in JavaScript
To convert a set to array in JavaScript we simply need to pass the set as a parameter in the JavaScript Array.from method. var numbers_set = new Set([11, 48, 101, 15, 41, 3, 13, 92]); var numbers_array = Array.from(numbers_set); console.log(numbers_array); #Output: [11, 48, 101, 15, 41, 3, 13, 92] Let’s take a look at another […]
Loop Through an Array of Objects in JavaScript
We can loop through an array of objects using JavaScript easily by using the JavaScript Array forEach() method. arrayOfObjects.forEach(function (eachObject) { console.log(eachObject); }); Let’s take a closer look at this below. Let’s say we have the following array of objects. Each object will have 3 properties. An id, first name, and last name. var office_workers […]
Remove Special Characters From String in JavaScript
To remove special characters from a string in JavaScript, the easiest way to do this is to use the JavaScript String replace() method. someString.replace(/[^a-z0-9]/gi, ""); The regex in our code /[^a-z0-9]/gi will target any character that isn’t a letter or number. Let’s see this code in action below. var someString = "Th##is $is$ a% s_ho-rt** […]
Remove Multiple Characters From String in JavaScript
To remove multiple characters from a string in JavaScript, the easiest way to do this is to use the JavaScript String replace() method. someString.replace(/[sh]/, ""); Where the characters s and h in the code above can be any characters and as many characters as you want. Let’s see this code in action below. var someString […]
Using JavaScript to Remove Character From String
We can use JavaScript to remove a character from a string easily by using the JavaScript String replace() method. someString.replace("s", ""); Let’s see this code in action below. var someString = "This is a short sentence." someString = someString.replace("s", ""); console.log(someString); #Output: Thi is a short sentence. When using string variables in JavaScript, we can […]
innerHTML vs outerHTML
The main difference between innerHTML vs outerHTML is that the innerHTML property will get the HTML code that is inside of a div or element, while the outerHTML property will get the innerHTML plus the HTML code of the div or element itself. The best way to show the difference is with some simple examples. […]
outerHTML – How to Get and Change the outerHTML Property of an Element
We can get and change the outerHTML of an element using JavaScript. We can use the JavaScript getElementById() method to target the outerHTML property of an element. document.getElementById("p1").outerHTML Let’s see an example of this below. Let’s say we have the following HTML: <div id="div1"> <p id="p1">This is a paragraph with some text.<p> </div> If we […]
Adding CSS Important Property Using JavaScript
There are a couple of ways we can add a CSS style as important using JavaScript. The best way we have found is to simply use the Style setProperty() method and target a specific style attribute. document.getElementById("p1").style.setProperty("color", "red", "important"); If we wanted to do this to a div that only had a class and not […]
JavaScript Power Operator
In JavaScript, the Power Operator, or exponentiation operator, **, is used to raise a number to the power of an exponent. var num = 2**4; The output of the code above would be the number 16. Some other examples of the power operator are below: var num1 = 6**1; var num2 = 2**2; var num3 […]
Using JavaScript to Set Select to the First Option
We can use JavaScript to set select to the first option by using the getElementById() and getElementsByTagName() methods and targeting the value property. document.getElementById("select-element").value = document.getElementById("select-element").getElementsByTagName('option')[0].value; Let’s see an example of this below. Lets say we have the following HTML: <div id="div1"> <select id="select1"> <option value="car">Car</option> <option value="bus" selected>Bus</option> <option value="train">Train</option> </select> <div id="click-me" onclick="changeSelect()">Change […]
Using JavaScript to Check a Radio Button
We can use JavaScript to check a radio button by making use of the getElementById() method along with targeting the checked property value. We simply need to change the checked property value of the radio button to true. Here is how we can do this: document.getElementById("radioButton").checked = true; Let’s see an example of this below. […]
Using JavaScript to Get Radio Button Value
We can use JavaScript to get the radio button value using the querySelector method along with the value property. document.querySelector('input[name="radio1"]:checked').value; Where radio1 in the code above would be the name attribute that all of the radio buttons share. Let’s see an example of this below. Lets say we have the following HTML: <div id="div1"> <p>Select […]
Using JavaScript to Check if Variable Exists
One of the easiest ways we can use JavaScript to check if a variable exists is with exception handling using a try-catch statement. try{ console.log(some-variable); } catch(err) { console.log("variable doesn't exist"); } #Output: variable doesn't exist This way will make sure that if you try to check if a variable exists that has not been […]
Using JavaScript to Remove All Non-Alphanumeric Characters From a String
In JavaScript, we can remove all non-alphanumeric characters from a string easily by making use of the JavaScript String replace() method and a regex expression. var someString = "!This is $a )string_with Non-Alphanumeric characters@"; someString = someString.replace(/[^0-9a-z]/gi, ''); console.log(someString); #Output: ThisisastringwithNonAlphanumericcharacters Notice in the replace method above, that instead of using .replace("/[^0-9a-z]/", '') we use […]
Get a List of Prime Numbers Using JavaScript
We can create a list of prime numbers in JavaScript easily – all we need is a custom function to check if a number is prime or not. We have a post on how to see if a number is prime or not, so we will use the function isPrime from that post to help […]
Set Hidden Field Value In JavaScript
We can set a hidden field value in a form in JavaScript by changing the type property of the field with the help of the getElementById() method. document.getElementById("someField").type = "hidden"; The above code would change the property type to hidden. Let’s take a look at an example below: Let’s say we have the following HTML […]
Check That String Does Not Contain Character in JavaScript
We can use JavaScript to check that a string does not contain a specific character by using the JavaScript indexOf() method. var someString = "Hello how are you today?" var charCheck = someString.indexOf('x'); //If charCheck == -1, then the string does not contain the character In our code above, if the variable charCheck is equal […]
Using JavaScript to Get the Domain From URL
We can use JavaScript to get the domain from the URL of the page we are on by using the window object and getting the location.host property of it. So the property window.location.host will return the current domain from the URL you see at the top of your browser. var curr_domain = window.location.host; console.log(curr_domain); #Output […]
Add Commas to Number in JavaScript
We can add commas to a number in JavaScript by using the JavaScript toLocaleString() method. var num = 1234; var commaNum = num.toLocaleString(); When working with numbers in JavaScript, many times you need to format those numbers a certain way. One such situation is if you want to add commas to numbers in your program […]
How to Clear a Textarea Field In JavaScript
We can clear a textarea field using JavaScript easily by making use of the value property. We simply need to set the value of the textarea field to an empty string. document.getElementById("textarea1").value = ""; Let’s see a quick example of this below: Let’s say we have the following HTML: <div id="div1"> <textarea type="text" id="userText">This is […]
How to Clear an Input Field in JavaScript
We can clear an input field using JavaScript easily by making use of the value property. We simply need to set the value of the input field to an empty string. document.getElementById("input1").value = ""; Let’s see a quick example of this below: Let’s say we have the following HTML: <div id="div1"> <input type="text" id="userText" value="This […]
Using JavaScript to Get URL Hash
We can use JavaScript to get the URL hash of the current page we are on by using the window object and getting the location.hash property of it. So the property window.location.hash will return the current hash part of the URL that you see at the top of your browser. Since this page does not […]
Using JavaScript to Get the URL Path
We can use JavaScript to get the URL path of the current page we are on by using the window object and getting the location.pathname property of it. So the property window.location.pathname will return the current URL path that you see at the top of your browser. var curr_path_url = window.location.pathname; console.log(curr_path_url); #Output /javascript-get-url-path/ Using […]
Using JavaScript to Get the Host URL
We can use JavaScript to get the host URL of the current page we are on by using the window object and getting the location.host property of it. So the property window.location.host will return the current host URL that you see at the top of your browser. var curr_host_url = window.location.host; console.log(curr_host_url); #Output theprogrammingexpert.com Using […]
Using JavaScript to Get the Base URL
We can use JavaScript to get the base URL of the current page we are on by using the window object and getting the location.origin property of it. So the property window.location.origin will return the current base URL that you see at the top of your browser. var curr_base_url = window.location.origin; console.log(curr_base_url); #Output //https://theprogrammingexpert.com Using […]
Using JavaScript to Check If String is a Number
There are a couple of ways that we can use JavaScript to check if a string is a number. We will start with one of the easiest ways which is to use the JavaScript isNaN() method. var stringNum = "1234"; console.log(isNaN(stringNum)); #Output false The isNAN() method stands for is “Not a Number”. So in our […]
Insert Character Into String In JavaScript
We can insert a character into a string in JavaScript by using the JavaScript String substring() method. To insert a character into a string, we will need an index position for where to put it. someString = someString.substring(0, indexPosition) + 'r' + someString.substring(indexPosition); Where indexPosition in the above code is the index of the character […]
Using JavaScript to Get Substring Between Two Characters
We can use JavaScript to get the substring between two characters by using the JavaScript String substring(), indexOf(), and lastIndexOf() methods. var newString = someString.substring(someString.indexOf("FirstCharacter")+1,someString.lastIndexOf("LastCharacter")); Where someString is the string we want to get the substring from, FirstCharacter is the character we want to start the substring after, and LastCharacter is the character we want […]
Using JavaScript to Generate a Random Float Between 0 and 1
We can use JavaScript to generate a random float between 0 and 1 by making use of the JavaScript Math.random() method. var randFloat = Math.random(); We can put this in a loop to generate a bunch on random floats between 0 and 1. for ( var i = 0; i < 5; i++ ) { […]
Using JavaScript to Check if a Number is Divisible by 3
We can use JavaScript to check if a number is divisible by 3 by using the JavaScript built-in remainder operator %. We divide the number by 3; if the remainder after division is 0, then the number is divisible by 3. If it is not 0, then the number is not divisible by 3. Here […]
Using JavaScript to Check if a Number is Divisible by 2
We can use JavaScript to check if a number is divisible by 2 by using the JavaScript built-in remainder operator %. We divide the number by 2; if the remainder after division is 0, then the number is divisible by 2. If it is not 0, then the number is not divisible by 2. Here […]
Using JavaScript to Check if Number is Divisible by Another Number
We can use JavaScript to check if a number is divisible by another number by using the JavaScript built-in remainder operator %. If the remainder after division is 0, then the number is divisible by the number you divided by. if ((x % y) == 0){ return true; //number is divisible by other number } […]
Using JavaScript to Count Even Numbers in an Array
There are a couple of ways we can use JavaScript to count the even numbers in an array. One of the simplest ways is to just use a for loop to loop through each number in the array and count the even ones. var count = 0; for ( var i = 0; i<someArray.length; i++ […]
Clicking on an Image to Enlarge it in HTML
In HTML, we can click on an image to enlarge it with the help of the JavaScript getElementById() method and by targeting the width and height properties of the image. The best way to show this is with an example. Let’s say we have the following HTML: <div id="div1"> <img id="image1" width="150px" height="150px" src="https://theprogrammingexpert.com/wp-content/uploads/example-img1.png"> </div> […]
Using JavaScript to Reverse a Number
We can use JavaScript to reverse a number easily by using converting the number into a string and then applying some JavaScript methods to reverse the string before we convert the string back to a number. We will make use of the JavaScript split(), reverse() and join() methods. Below is a function we will create […]
Using JavaScript to Add Item to Array if it Does Not Exist
We can use JavaScript to add an item to an array if it does not already exist in the array by making use of the indexOf() and push() methods. var someArray = ["a","b","c"]; if( someArray.indexOf("d") == -1 ){ someArray.push("d"); } console.log(someArray); #Output ['a', 'b', 'c', 'd'] In the code above, we simply have an if-else […]
Using JavaScript to Add Seconds to a Date
We can use JavaScript to add seconds to a date by using the JavaScript getTime() method. The getTime() method converts dates into the number of milliseconds since January 1st, 1970. Since there are 1000 milliseconds in 1 second, we can add multiples of 1000 to our converted date to add as many seconds as we […]
How to Remove Decimals of a Number in JavaScript
The easiest way to remove the decimals of a number in JavaScript is by using the Math.trunc() method. var noDecimalNumber = Math.trunc(9.31); We can wrap this code in a function to simplify the whole process. You simply enter in a number, and the function will return the number with no decimal places. function noDecimalNumber(num){ return […]
Using JavaScript to Get the Decimal Part of a Number
There are a couple ways we can use JavaScript to get the decimal part of a number. One of the easiest ways is to convert the number into a string and make use of the JavaScript split() method. Here is an example of how to do this: var num = 123.456; var numToString = num […]
Using JavaScript to Remove All Pipe Characters From String
In JavaScript, we can remove all pipe characters from a string easily by making use of the JavaScript String replace() method. var someString = "|This is |a |string with pipe characters|"; someString = someString.replace(/\|/g, ''); console.log(someString); #Output: This is a string with pipe characters Since pipe characters are special characters we must escape them by […]
How to Remove Non Numbers From String in JavaScript
We can easily remove all non numbers from a string using JavaScript by making use of the JavaScript String replace() method along with the RegEx \D metacharacter. var someString = "This12 is34 5a st5ri6n7g with numbe88877777rs90."; someString = someString.replace(/\D/g, ''); console.log(someString); #Output: 123455678887777790 Notice in the replace method above, that instead of using .replace(/\D/, '') […]
How to Remove All Numbers From String in JavaScript
We can remove all numbers from a string using JavaScript easily by making use of the JavaScript String replace() method. var someString = "This12 is34 5a st5ri6n7g with numbe88877777rs90."; someString = someString.replace(/[0123456789]/g, ''); console.log(someString); #Output: This is a string with numbers. Notice in the replace method above, that instead of using .replace(/[0123456789]/, '') we use […]
Using JavaScript to Remove Forward Slash From String
In JavaScript, to remove a forward slash from a string, the easiest way is to use the JavaScript String replace() method. var someString = "/This is /a /string with forward slashes/"; someString = someString.replace(/\//g, ''); console.log(someString); #Output: This is a string with forward slashes Since forward slashes are special characters we must escape them by […]
Using JavaScript to Remove Backslash From a String
In JavaScript, to remove a backslash from a string, the easiest way is to use the JavaScript String replace() method. var someString = "\\This is \\a \\string with backslashes"; someString = someString.replace(/\\/g, ''); console.log(someString); #Output: This is a string with backslashes Since backslashes are special characters we must escape them by putting a backslash in […]
Remove Braces from String Using JavaScript
We can remove braces from a string in JavaScript easily by using the JavaScript String replace() method. var someString = "{This is }a {string with braces}" someString = someString.replace(/\{/g, ''); someString = someString.replace(/\}/g, ''); console.log(someString); #Output: This is a string with braces Since braces are special characters we must escape them by putting a backslash […]
Get the Size of a Set in JavaScript
We can use JavaScript to get the set size by simply using the size property of the set. The size property will simply return the number of items in the set. var someSet = new Set(["this","is","a","set","of","size","7"]); var length_Of_Set = someSet.size; console.log(length_Of_Set); #Output 7 In JavaScript, it can be useful to be able to easily calculate […]
Using JavaScript to Replace Multiple Characters in a String
We can use JavaScript to replace multiple characters in a string by using the JavaScript String replace() method. text.replace(/z|y/g, 'x'); In the code above, z and y are the characters we want to replace, and x is the character we will replace them with. Let’s say we have the following HTML: <div id="div1"> <p id="p1">This […]
Remove Undefined Values From an Array in JavaScript
To remove undefined values from an array using JavaScript, one of the easiest ways to do this is to use a for loop with an if conditional statement. Here is a simple function we will create to remove undefined values from an array. function removeUndefinedValues(arr){ var new_array = []; for (var i=0; i<arr.length; i++){ if( […]
Using JavaScript to Get Image Dimensions
We can use JavaScript to get the dimensions of an image easily by using the Style height and width properties. var someImage; var imageWidth = someImage.width; var imageHeight = someImage.height; Let’s see how simple this can be using the following image from our site. Here is the HTML code: <img id="home-page-image" style="width:400px; height:300px;" src="http://theprogrammingexpert.com/wp-content/uploads/2021/12/tpe-main2-e1638420493699.jpg"> And […]
Using JavaScript to Remove Null Values From an Array
We can use JavaScript to remove null values from an array by making use of a for loop with an if conditional statement. Here is a simple function we will create to remove nulls from an array. function removeNullValues(arr){ var new_array = []; for (var i=0; i<arr.length; i++){ if( arr[i] != null ){ new_array.push(arr[i]); } […]
How to Create a New h1 Element With JavaScript
We can create a new h1 element with JavaScript by using the createElement() method along with the innerHTML property. var newh1 = document.createElement("h1"); newh1.innerHTML = "This is a new h1 element." And that’s it. Let’s go over creating a new h1 element with JavaScript and adding it to the DOM. In this simple example, we […]
Using JavaScript to Check if Variable is a Function
One of the easiest ways we can use JavaScript to check if a variable is a function is by using the JavaScript typeof Operator in an if conditional statement. if ( typeof someVariable == "function" ){ //The variable IS a function } In the code above, someVariable is the variable that we want to check […]
Using JavaScript to Check if Variable is an Object
One of the easiest ways we can use JavaScript to check if a variable is an object is by using the JavaScript typeof Operator in an if conditional statement. if ( typeof someVariable == "object" ){ //The variable IS an object } In the code above, someVariable is the variable that we want to check […]
Using JavaScript to Check if Variable is a Number
One of the easiest ways we can use JavaScript to check if a variable is a number is by using the JavaScript typeof Operator in an if conditional statement. if ( typeof someVariable == "number" ){ //The variable IS a number } In the code above, someVariable is the variable that we want to check […]
Using JavaScript to Add Trailing Zeros
In JavaScript, we can convert an integer to a string and add trailing zeros to it by making use of the addition operator (+). Let’s say we have the integer 456 and we want to add 3 zeros to the end of it. Here is the code to do this: var num = 456; var […]
Using JavaScript to Check if Variable is a String
One of the easiest ways we can use JavaScript to check if a variable is a string is by using the JavaScript typeof Operator in an if conditional statement. if ( typeof someVariable == "string" ){ //The variable IS a string } In the code above, someVariable is the variable that we want to check […]
Using JavaScript to Remove Trailing Zeros From a Number or String
There are a couple of ways that we can use JavaScript to remove trailing zeros from a string or number. We will first look at removing trailing zeros from a string. To do this, we simply need to use the replace() method with a regular expression. Here is our code to do this: var numString […]
Using JavaScript to Add Leading Zeros
In JavaScript, we can convert an integer to a string and add leading zeros to it by making use of the addition operator (+). Let’s say we have the integer 456 and we want to add 3 zeros to the front of it. Here is the code to do this: var num = 456; var […]
Using JavaScript to Remove Leading Zeros
In JavaScript, there are a couple of ways that we can remove leading zeros from a string. The easiest way is to simply use the JavaScript parseInt() method. var num = '0000123'; var newNum = parseInt(num, 10); And that’s it. We can wrap our code in a simple function so that we can remove the […]
How to Split a Number into Digits in JavaScript
There are a number of ways we can split a number into digits in JavaScript. One of the simplest ways to do this is to convert the number into a string, iterate over it, and create a new array of digits. Here is the code of how to do this, and then we will explain […]
Convert an Array to Set in JavaScript
To convert an array to a set in JavaScript we simply just need to pass the array as a parameter when creating a new set, new Set(). One of the main differences between an array and a set is that a set does not contain duplicate values. var numbers_array = [13, 48, 92, 13, 48, […]
Using JavaScript to Get the Page Title
In JavaScript, to get the page title of a post or article we can simply use the Document Object to do this. Almost all of the time, the title of an article or page will be in the title tag <title>Some title</title>. So to retrieve the title from the title tag, we simply need to […]
Using JavaScript to Multiply All Elements in an Array
In JavaScript, we can multiply all elements in an array easily by making use of a for loop. We simply loop through all elements in the array and multiply them together. Here is some simple code to do this: var array_of_numbers = [9,3,2,4]; var total = array_of_numbers[0]; for( var i=1; i<array_of_numbers.length; i++ ){ total = […]
Remove All Instances of Value From an Array in JavaScript
To remove all instances of a value from an array in JavaScript, the easiest way is to use the JavaScript array filter() function. Below shows an example of how you could remove the number ‘1’ from an array of numbers with filter(). var array_of_numbers = [1,2,3,4,1,2,1,4,3,2]; var filtered_array = array_of_numbers.filter(x => x != 1); console.log(filtered_array); […]
JavaScript Print Array – Printing Elements of Array to Console
In JavaScript, we can print an array using a couple of methods. The easiest way to print an array using JavaScript is to use the console.log() method. The first example shows how to print an array using just the console.log() method. var anArray = ["This","is","a","array","of","strings"]; console.log(anArray); #Output: ['This', 'is', 'a', 'array', 'of', 'strings'] If we […]
Create Array of Zeros in JavaScript
In JavaScript, we can easily create an array of zeros. The easiest way to create an array of zeros only is to use the javascript array fill() method. var array_of_zeros = Array(10); array_of_zeros.fill(0); console.log(array_of_zeros); #Output: [0,0,0,0,0,0,0,0,0,0] A second way to make an array of zeros in JavaScript is to use a for loop. var array_of_zeros […]
Remove Empty Strings from an Array in JavaScript
To remove empty strings from an array using JavaScript, one of the easiest ways to do this is to use a for loop with an if conditional statement. Here is a simple function we will create to remove empty strings from an array. function removeEmptyStrings(arr){ var new_array = []; for (var i=0; i<arr.length; i++){ if( […]
Check if a String Contains Uppercase Letters in JavaScript
We can check if a string contains uppercase characters in JavaScript by checking each letter to see if that letter is uppercase in a loop. We will make use of the toUpperCase() and charAt() methods. Here is our function that will check if there are any uppercase letters in a string. function checkUppercase(str){ for (var […]
Remove Commas From a String in JavaScript
To remove commas from a string in JavaScript the easiest way is to use the JavaScript String replace() method. someString.replace(/,/g, ""); Here is the code with a simple example: var commaString = "This, is, a, string, with, commas."; commaString = commaString.replace(/,/g, ""); console.log(commaString); #Output: This is a string with commas. Notice in the replace method […]
How to Swap Values in an Array in JavaScript
We can swap values in an array in JavaScript easily by making use of a temporary variable. The easiest way to show how this is done is with an example. var someArray = [value1,value2]; var temp = someArray[0]; someArray[0] = someArray[1]; someArray[1] = temp; Lets show a really simple example using this code: var someArray […]
How to Find the Longest String in an Array in JavaScript
We can find the longest string in an array in JavaScript by using a loop to go over each element of the array, get the length of that element, and compare it to the other strings to see if it is longer. Here is a function that will get the longest string in an array […]
Check if Character is Uppercase in JavaScript
We can check if a character is uppercase in JavaScript by checking if the letter is equal to the letter after applying the JavaScript toUpperCase() method. Here is a simple function to do this: function checkCharUpper(letter){ return letter == letter.toUpperCase(); }; Here is the function in use with an a couple of examples: function checkCharUpper(letter){ […]
Reverse a String in JavaScript
We can easily reverse a string in JavaScript using the JavaScript split(), reverse() and join() methods. Below is a function we will create to reverse a string. function reverseString(str){ var newStringArr = str.split(""); newStringArr.reverse(); newStringArr = newStringArr.join(""); return newStringArr; }; Here is the function in use with an example string: function reverseString(str){ var newStringArr = […]
Reverse Words in a String JavaScript
We can easily reverse words in a string in JavaScript using the JavaScript split(), reverse() and join() methods. Below is a function we will create to reverse words in a string. function reverseWords(str){ var newString = str.split(" "); newString.reverse(); newString = newString.join(" "); return newString; }; Here is the function in use with an example […]
Remove the First and Last Character From a String in JavaScript
We can remove the first and last character from a string using JavaScript easily with the use of the String slice() method. var newString = oldString.slice(1,-1); The code above will return the original string minus the first and last characters. Let’s say we have the following JavaScript: var someString = "This is some example text"; […]
JavaScript Capitalize First Letter of Every Word
In JavaScript, we can capitalize the first letter of every word in a string easily with the help of a bunch of JavaScript String and Array methods. Here is our function to do this: function capitalizeFirstLetter(str){ var new_strings = str.split(" "); var new_string = []; for ( var i=0; i<new_strings.length; i++ ){ new_strings[i] = new_strings[i].charAt(0).toUpperCase() […]
JavaScript Round to Nearest 10
In JavaScript, we can round to the nearest 10 easily with the help of the JavaScript Math.round() method. The JavaScript round() method rounds to the nearest whole number, but we can make an adjustment by dividing the input to our function by 10, and then multiplying by 10. Here is our function below that will […]
Remove Parentheses From String Using JavaScript
In JavaScript, to remove parentheses from a string the easiest way is to use the JavaScript String replace() method. var someString = "(This is )a (string with parentheses)"; someString = someString.replace(/\(/g, ''); someString = someString.replace(/\)/g, ''); console.log(someString); #Output: This is a string with parentheses Since parentheses are special characters we must escape them by putting […]
JavaScript Check if Attribute Exists in HTML Element
Using JavaScript, the easiest way to check if an attribute exists in an HTML element is to use the hasAttribute() method. element.hasAttribute("href") Here we can see how we can use this information in an if-else statement. if (element.hasAttribute("href")){ console.log("HTML element has attribute href!"); } else { console.log("HTML element does not have attribute href!"); } And […]
How to Repeat Character N Times in JavaScript
In JavaScript, we can repeat a character n times by making use of the JavaScript String repeat() method. var characterToRepeat = "s"; characterToRepeat = characterToRepeat.repeat(10); console.log(characterToRepeat); #Output: ssssssssss When using string variables in JavaScript, we can easily perform string manipulation to change the value of the string variables. One such manipulation is repeating a character […]
How to Repeat a String in JavaScript
In JavaScript, we can easily repeat a string as many times as we would like. The easiest way to repeat a string n times is to use the JavaScript String repeat() method. var stringToRepeat = "string"; stringToRepeat = stringToRepeat.repeat(3); console.log(stringToRepeat); #Output: stringstringstring When using string variables in JavaScript, we can easily perform string manipulation to […]
JavaScript Coin Flip – How to Simulate Flipping a Coin in JavaScript
In JavaScript, we can simulate a coin flip and get a random result using the JavaScript Math.random() method along with an if else conditional statement. var headsOrTails; if ( Math.random() > .5 ){ headsOrTails = "Heads"; } else { headsOrTails = "Tails"; } Being able to generate random numbers efficiently when working with a programming […]
JavaScript Random Boolean – How to Generate Random Boolean Values
In JavaScript, we can easily get a random boolean using the JavaScript Math.random() method along with an if else conditional statement. var booleanValue; if ( Math.random() > .5 ){ booleanValue = true; } else { booleanValue = false; } Being able to generate random numbers efficiently when working with a programming language is very important. […]
Remove Vowels From String In JavaScript
To remove vowels from a string in JavaScript, the easiest way to do this is to use the JavaScript String replace() method with a regex expression. someString.replace(/[aeiou]/g, ""); Let’s see this in a full example using text from our About page. var someString = "This blog is a compilation of a programmer’s findings in the […]
Remove Word From String In JavaScript
To remove a word from a string in JavaScript, the easiest way to do this is to use the JavaScript String replace() method. someString.replace("theWord", ""); Let’s see this in a full example. var someString = "This is a short sentence." someString = someString.replace("short", ""); console.log(someString); #Output: This is a sentence. Let’s take a look at […]
Remove Brackets from String Using JavaScript
In JavaScript, to remove brackets from a string the easiest way is to use the JavaScript String replace() method. var someString = "[This is ]a [string with brackets]" someString = someString.replace(/\[/g, ''); someString = someString.replace(/\]/g, ''); console.log(someString); #Output: This is a string with brackets Since brackets are special characters we must escape them by putting […]
Using JavaScript to Remove Apostrophe From a String
In JavaScript, to remove an apostrophe from a string the easiest way is to use the JavaScript String replace() method. var someString = "I'm looking for the dog's collar." someString = someString.replace(/'/g, ''); console.log(someString); #Output: Im looking for the dogs collar. Notice in the replace method above, that instead of using .replace(“‘”, ”) we use […]
Sum the Digits of a Number in JavaScript
To sum the digits of a number in JavaScript, we can use a for loop which will get each digit from the number and add them together. Here is a quick function that will take a number and then sum it’s digits: function sumDigits(num){ var sum = 0; var numString = num + ""; for […]
How to Generate a Random Letter In JavaScript
To generate a random letter using JavaScript, we can build a custom function that uses the JavaScript random() method along with the charAt() method. Here is our function below to generate a random letter In JavaScript: function randomLetter() { var letters = 'abcdefghijklmnopqrstuvwxyz'; var randomNum = Math.round(Math.random() * 26); var randomLetter = letters.charAt(randomNum); return randomLetter; […]
JavaScript Check If Number is a Whole Number
In JavaScript, the easiest way to check if a number is a whole number is by using the Number.isInteger() method. console.log(Number.isInteger(2.0)) console.log(Number.isInteger(2.1)) #Output: True False In JavaScript, when working with numbers, it can be useful to be able to find out if a number is a whole number. We can easily check if a number […]
Using JavaScript to Remove Quotes From a String
In JavaScript, to remove quotes from a string the easiest way is to use the JavaScript String replace() method. You can remove single and double quotes using replace(). var singleQuoteString = "This' is' a' string' with' quotes." var doubleQuoteString = 'This" is" a" string" with" quotes.' singleQuoteString = singleQuoteString.replace(/'/g, ''); doubleQuoteString = doubleQuoteString.replace(/"/g, ''); console.log(string_without_single); […]
Convert an Array of Values into a String Without Commas in JavaScript
In JavaScript, we can convert an array of elements into to string without commas easily using the Array join() method. var arrayOfColors = ["Red", "Green", "Blue", "Orange", "Yellow"]; var stringOfColors = arrayOfColors.join(" "); The join method will convert an array of values into a string for us just using the join() method as is. This […]
How in JavaScript to Get the Day of the Week
In JavaScript, we can get the day of the week using the getDay() method. This will return a number from 0-6, with 0 being Sunday, and 6 being Saturday. var currDate = new Date(); var currDayOfWeek = currDate.getDay(); The value of currDayOfWeek in the code above would return whatever the day of the week it […]
Adding an Underline with JavaScript
To underline a paragraph using JavaScript, we can simply use the style textDecoration property. document.getElementById("p1").style.textDecoration = "underline"; Let’s say we have the following HTML: <div id="div1"> <p id="p1">We will change this text to be undelined.</p> </div> If we want to add an underline to the paragraph, we will use the textDecoration property in the following […]
Using JavaScript to Set Visibility
We can use JavaScript to set the visibility of an element by using the JavaScript getElementById() method along with the visibility property. document.getElementById("div1").style.visibility = "visible"; The code above will make sure #div1 is visible. document.getElementById("div1").style.visibility = "hidden"; The code above will make sure #div1 is hidden from view, but it will still take up space. […]
Using JavaScript to Increment a Variable by 1
In JavaScript, we can increment a variable by 1 easily by using the increment operator (++). someVaraible++; The above code would be the equivalent of: someVaraible = someVaraible + 1; Let’s see a simple example of this below. In the example below, we will have an array of numbers that we will want to get […]
Set Text with the textContent Property in JavaScript
We can use the textContent property in JavaScript to set the text of an HTML element. document.getElementById("div1").textContent = "Some Text"; Let’s say we have the following HTML: <div id="div1"></div> If we want to add some text to the div, #div1, we can use the textContent property to do this with the following JavaScript code. document.getElementById("div1").textContent […]
How to Empty a String in JavaScript
It is very easy to empty a string in JavaScript. All you have to do is set the string to an empty string. var someString = "This is some text"; someString = ""; To empty the string, someString, in the code above, we just have to set the variable to an empty string, someString = […]
JavaScript continue statement – Skip Iterations in Loop Based on Conditions
We can use the JavaScript continue statement to skip over certain conditions in a for or while loop. The best way to understand the continue statement is with an example. var count = 0; for (var i = 0; i < 20; i++) { if (i == 5) { continue; } //If the above condition […]
JavaScript join – Create String from Elements in an Array
We can use the JavaScript join() method to convert an array of values into a string. var arrayOfColors = ["Red", "Green", "Blue", "Orange", "Yellow"]; var stringOfColors = arrayOfColors.join(); Let’s take a look at a simple example below. Let’s say we have a simple array of colors and we want to convert the array to a […]
How to Use JavaScript to Round Up Numbers
In JavaScript, to always round a number up, we can do this very easily by using the Math.ceil() method. var num = Math.ceil(1.6); The above code would round the number 1.6 UP to 2. We have already written a post about the Math.ceil() method which you can learn more about here. However, with the ceil() […]
Using JavaScript to Round to 1 Decimal
In JavaScript, to round a number to 1 decimal place we can use the Math.round() method in the following JavaScript code: var roundedNumber = Math.round(num * 10) / 10; In the code above, num will be the number that we want to round to 1 decimal place. So if we want to round the number […]
Using JavaScript to Round to 2 Decimal Places
In JavaScript, to round a number to 2 decimal places we can use the Math.round() method in the following JavaScript code: var roundedNumber = Math.round(num * 100) / 100; In the code above, num will be the number that we want to round to 2 decimal places. So if we want to round the number […]
How to Return Multiple Values in JavaScript
In JavaScript, the easiest way to return multiple values is to store them in an array and return the array. function someFunction(){ var arrayToReturn = [2,3]; return arrayToReturn; }; In the code above, we wanted to return the values 2 and 3, so we create a new array, arrayToReturn, and then return that array. This […]
Using JavaScript to Set the Cursor Position
In JavaScript, we can set the cursor position very easily using the focus() method. document.getElementById("someInputField").focus(); We usually will want to set the cursor position to an input field to get the user’s attention to a form. We can also set the cursor potion right after the page loads. To do this we will use the […]
How to Get the Cursor Position in JavaScript
To get the cursor position in JavaScript, we can use the MouseEvent client properties, that is the clientX Property and the clientY Property. event.clientX event.clientY To get the cursor position we will need to attach a mouse event to either a div on the page or to the whole page document itself. We will need […]
Using JavaScript to Declare Multiple Variables
In JavaScript, we can declare multiple variables either all at once or do it one line at a time. Here is the code for doing it all at once. var someVariable1, someVariable2, someVariable3, someVariable4; This way uses less code, but can be harder for some to read/maintain. We prefer just putting one variable per line […]
Using JavaScript to Get the Last Day of the Month
In JavaScript, we can get the last day of the month with the help of the new Date() constructor and come JavaScript code. var currDate = new Date(); var currMonth = currDate.getMonth(); var currYear = currDate.getFullYear(); var newDate = new Date(currYear, currMonth + 1, 0); var lastDayOfMonth = newDate.toString(); We first will get the current […]
Using JavaScript to Hide Element by Class
In JavaScript to hide an element by its class name, we can do this by using the getElementsByClassName() method along with a for loop. var selectedClasses = document.getElementsByClassName('class-to-hide'); for (var i = 0; i < selectedClasses.length; i++) { selectedClasses[i].style.display = 'none'; } In the code above, we use the getElementsByClassName() method to return a collection […]
JavaScript Infinite Loop
A JavaScript infinite loop is one of the most dreaded errors when coding in JavaScript because the code inside the loop will just run forever. This can be dangerous if there is a lot of code inside the loop, as it will use a ton of your browser’s resources and usually cause a crash. Here […]
Using JavaScript to Run a Function Every 5 seconds
We can use JavaScript to run a function every 5 seconds with the help of the setInterval() method. setInterval(function(){ //Code that will run every 5000 milliseconds or 5 seconds }, 5000); In the code above, the setInterval() method will run the function in it’s first parameter every 5000 milliseconds, or 5 seconds. We can change […]
Using JavaScript to Redirect After 5 Seconds
In JavaScript, we can redirect the page after 5 seconds with the help of the setTimeout method and the window.location object. setTimeout(function(){ window.location.href = "http://theprogrammingexpert.com/"; }, 5000); You can see in the code above that the setTimeout() method will run the function after 5000 milliseconds. We can change that parameter to be however long we […]
How to Create a JavaScript Count Up Timer
In JavaScript, we can make a count up timer somewhat easily with the help of the setTimeout and setInterval methods. setTimeout(function(){ //Code that will run after 5 seconds }, 5000); setInterval(function(){ //Code that will run every 1 second }, 1000); You can see in the code above that the setTimeout() method will run the function […]
JavaScript offsetTop – Get the Top Position of Element
We can use JavaScript and the offsetTop property of an element to get the top position of that element. document.getElementById("div1").offsetTop; The offsetTop property will return the top position of the element relative to the page. Note that we can also get the top position of an element using jQuery using the offset() method. Using JavaScript […]
Using JavaScript to Get the Scroll Position
While scrolling a webpage, we can use JavaScript to get the scroll position of the top of the window using the scrollTop property. document.documentElement.scrollTop The scrollTop property will return the top position of the element it is called on. In this case, we use it on the webpage document we are on so it will […]
Using JavaScript to Scroll to Bottom of Div
We can use JavaScript to scroll to the bottom of a div by using the scrollTo method along with the offsetTop and offsetHeight properties. window.scrollTo({ top: (topPositionOfDiv+heightOfDiv), behavior: 'smooth' }); Let’s say I have the following HTML: <div id="div1">Div to scroll to the bottom of.</div> To scroll to the bottom of the div, we can […]
Using JavaScript to Scroll to the Top of the Page
We can use JavaScript to scroll to the top of the page by using the scrollTo method along with the top and behavior properties. window.scrollTo({ top: 0, behavior: 'smooth' }); Let’s say I have the following HTML: <div id="top-link">Top</div> To scroll to the top of the page, we can use the scrollTo() method and pass […]
Using JavaScript to Resize an Image
We can use JavaScript to resize an image easily by targeting the Style width and height properties and using the getElementById() method. document.getElementById("image1").style.width = "150px"; Let’s say we have the following HTML: <div id="div1"> <img id="image1" src="http://theprogrammingexpert.com/wp-content/uploads/example-img1.png"> </div> If we want to resize the image to be a set width and height, we can use […]
Changing the Background Image of a div in JavaScript
Changing the background image of a div using JavaScript is done simply by using the getElementById method along with the backgroundImage property. document.getElementById("div1").style.backgroundImage = "url('someImage.jpg')"; Let’s say we have the following HTML with the following style: <div id="div1" style="background-image: url('img.jpg');"></div> To change the background image of #div1 from img.jpg to anotherImg.jpg, we will use the […]
JavaScript isPrime – How to Check if a Number is Prime in JavaScript
To tell if a Number in JavaScript is prime, we can use the modulus (remainder) operator % along with an if conditional statement. We can make a simple function that will let us know if a number is prime or not. First, here is the JavaScript code that determines whether a number is prime or […]
Using Javascript to Remove the Id from a Div
We can use JavaScript to remove the id of a div by using the removeAttribute() method. document.getElementById("div1").removeAttribute("id"); Let’s say I have the following HTML: <div id="div1"> <p>This is a paragraph.</p> </div> If we want to remove the id of div “div1” in the HTML above, we can target that div and then use the removeAttribute() […]
Using JavaScript to Set the Id of an Element
We can use JavaScript to set the id of an element by combining the querySelector() method along with the id property. document.querySelector("#div1 p").id = "p1"; Let’s say I have the following HTML: <div id="div1"> <p>This is a paragraph.</p> </div> If we want to set the id of the paragraph to “p1” we can use the […]
How to Change the Id of an Element in JavaScript
To change the id of an element in JavaScript we can do this by combining the getElementById() method along with the id property. document.getElementById("div1").id = "div2"; Let’s say I have the following HTML: <div id="div1"> <p class="p">This is a paragraph.</p> </div> If we want to change the id of the div from “div1” to “div2” […]
How to Get the First Character of a String in JavaScript
We can get the first character of a string in JavaScript easily using the String substring() method. var firstCharacter = someString.substring(0,1); In the code above, firstCharacter will be the first character of the string. Let’s say we have the following JavaScript: var someString = "This is some example text"; var newString = someString.substring(0,1); In the […]
Using JavaScript to Show and Hide a Div
We can use JavaScript to show and hide a div using one button by combing the getElementById() method, the display property, and an if else conditional statement. var displayStatus = document.getElementById("someDiv"); if ( displayStatus.style.display == 'none' ){ displayStatus.style.display = 'block'; } else { displayStatus.style.display = 'none'; } We can use JavaScript to show a div […]
How to Hide a Div in JavaScript
We can hide a div in JavaScript easily by combing the getElementById() method along with the Style display property. document.getElementById("div1").style.display = "none"; Let’s say we have the following html: <div id="div1">This is a div that we can hide with JavaScript</div> Next, we want to hide the div, so we will use the element’s display property. […]
Using JavaScript to Show a Div
We can use JavaScript to show a div by combing the getElementById() method along with the Style display property. document.getElementById("div1").style.display = "block"; Let’s say we have the following html: <div id="div1">This is a hidden div that we can show with JavaScript</div> Next, we want to show the div, so we will use the element’s display […]
Using JavaScript to Replace a Character at an Index
In JavaScript, we can replace a character from a string at a specific index using the String substring() method. This is one of the easiest ways we have found to do this. someString = someString.substring(0, index) + 'r' + someString.substring(index + 1); Where index in the above code is the index of the character we […]
JavaScript onfocusout – How to Use the onfocusout Event on an HTML Form
The JavaScript onfocusout event will occur when an element (most of the time an input) loses the user’s focus. This occurs when either the user mouse clicks away from that element, or tabs away from it using the keyboard. <input type="text" onfocusout="someFunction()"> Let’s say we have the following HTML: <form> <label for="fname">Full Name:</label> <input type="text" […]
JavaScript onfocus – Changing Form Styles with the onfocus Event
The JavaScript onfocus event will occur when an element (most of the time an input) gets the user’s focus. This occurs when either the user mouse clicks onto the element, or tabs onto it using the keyboard. <input type="text" onfocus="someFunction()"> We can add a function call to the onfocus event and run some code when […]
Using JavaScript to Set the Width of a Div
We can use JavaScript to set the width of a div by using the Style width Property. document.getElementById("div1").style.width = "100px"; Let’s take a look at a simple example below. Let’s say we have the following HTML: <div id="div1"> <p>This paragraph is in a div that we want to set the width of.</p> </div> If we […]
Using JavaScript to Get the Width of an Element
We can use JavaScript to get the width of an element by using the offsetWidth property. document.getElementById("div2").offsetWidth; You can also get the width of an element using the width property, but one problem we see a lot is if no width is set for the element, nothing will be returned for the width. This is […]
Using JavaScript to Sort an Array of Strings
We can use JavaScript to sort an array of strings by using the JavaScript Array sort() method. var colors = ["Red", "Green", "Blue", "Orange","Yellow"]; colors.sort(); Let’s take a look at a simple example below. Let’s say we have a simple array of colors and we want to sort them. To do this we simply need […]
setInterval JavaScript – How to Repeat Code in Set Time Intervals
The setInterval() method in JavaScript will run a function or code in a set time interval that you can choose. setInterval(function(){ //Code that will run every 1000 milliseconds }, 1000); In the code above, the setInterval() method will run the function in it’s first parameter every 1000 milliseconds, or 1 second. We can change that […]
Using JavaScript to Compare Dates
We can use JavaScript to compare dates using the getTime() method. The JavaScript getTime() method converts dates into the number of milliseconds since January 1st, 1970. var date1 = new Date('2019-01-01'); var date2 = new Date('2020-01-01'); if (date1.getTime() < date2.getTime()) { console.log("date2 is after date1"); } else { console.log("date1 is after date1"); } // This […]
clearInterval JavaScript – How the clearInterval() Method in JavaScript Works
The clearInterval() method in JavaScript clears the timer which has been set by a setInterval() method. var interval = setInterval(function(){ //Code that will run every 1000 milliseconds if( //some condition ){ clearInterval(interval); } }, 1000); In the code above, the setInterval() method will run the function every 1000 milliseconds(1 second). We can change that parameter […]
How to Create a JavaScript Countdown Timer
In JavaScript, we can make a countdown timer somewhat easily with the help of the setTimeout and setInterval methods. setTimeout(function(){ //Code that will run after 5000 milliseconds }, 5000); setInterval(function(){ //Code that will run every 1000 milliseconds }, 1000); You can see in the code above that the setTimeout() method will run the function after […]
Using JavaScript to Wait 5 Seconds Before Executing Code
In JavaScript, we can wait 5 seconds before executing a function or some code with the use of the setTimeout method. setTimeout(function(){ //Code that will run after 5000 milliseconds }, 5000); You can see in the code above that the setTimeout() method has the second parameter of 5000. This is how long (in milliseconds) the […]
JavaScript Opacity – How to Change the Opacity of an Element Using JavaScript
In JavaScript, we can change the opacity of a div simply by using the CSS opacity property along with the getElementById() method. document.getElementById("div1").style.opacity = .2; Let’s say we have the following HTML: <style>#div1 { background: green; }</style> <div id="div1"> <p>This paragraph is in a div that we want to change the opacity of.</p> </div> If […]
Using JavaScript to Replace a Space with an Underscore
To replace a space with an underscore in a paragraph using JavaScript, we can use the JavaScript String replace() method. text.replace(/ /g, '_'); Let’s say we have the following HTML: <div id="div1"> <p id="p1">We will update the text: <span id="span1">text with underscore</span></p> </div> If we want to change the spaces in the span “text with […]
JavaScript isInteger – How to Check if a Number is an Integer
To tell if a number in JavaScript is an integer, we can use the JavaScript Number.isInteger() method. Number.isInteger(3) The above code would return true, since 3 in an integer. Some other examples of JavaScript isInteger method are below: var result1 = Number.isInteger(1); var result2 = Number.isInteger(0); var result3 = Number.isInteger(-10); var result4 = Number.isInteger(1.5); var […]
Swapping Images in JavaScript
Swapping Images in JavaScript is simple, we just have to use the image src property along with the getElementById method. document.getElementById("img1").src = "anotherImg.jpg"; Let’s say I have the following HTML code: <div id="div1"> <img id="img1" src="img.jpg"> </div> To swap the image above to another image, we can use the src property. We can change the […]
Using JavaScript to Get the Height of an Element
We can use JavaScript to get the height of an element by using the offsetHeight property. document.getElementById("div2").offsetHeight; You can also get the height of an element using the height property, but one problem we see a lot is if no height is set for the element, nothing will be returned for height. This is why […]
Set the Height of a Div Using JavaScript
To set the height of a div in JavaScript we can do this easily by using the Style height Property. document.getElementById("div1").style.height = "100px"; Let’s take a look at a simple example below. Let’s say we have the following HTML: <div id="div1"> <p>This paragraph is in a div that we want to set the height of.</p> […]
Using JavaScript to get Textarea Value
To get the value from a textarea field in JavaScript, we can use the value property. We can also use the value property to set the value of a textarea field. var userInput = document.getElementById("textarea1").value; Let’s say we have the following HTML: <form> <label for="desc">Description:</label> <textarea type="text" id="desc" name="desc"></textarea> <button type="submit" value="Submit">Submit</button> </form> To get […]
Using JavaScript to Capitalize the First Letter of a String
We can use JavaScript to capitalize the first letter of a string by combining the JavaScript String toUpperCase() and substring() methods. var theString = "how are you?" theString = theString.substring(0,1).toUpperCase() + theString.substring(1); Let’s look at an example below. We can create a simple function that will use JavaScript to capitalize the first letter of a […]
How to Exit for Loop in JavaScript
To exit a for loop in JavaScript we can use the break statement. The break statement will exit a loop when it is called inside of the loop. for (var i = 0; i < someArray.length; i++) { if ( a > b ) { break; } } Let’s take a look at a simple […]
parseInt() JavaScript – Convert String to Integer with parseInt() method
The parseInt() JavaScript method will parse the value given to it as a string and then return the first Integer in the string. This is done using the parseInt() method. var num = parseInt("20.12345"); The above code would return the number 20. Some other examples of the parseInt() method are below: var num1 = parseInt(1.9); […]
lastIndexOf JavaScript – Get the Last Position of a String in Another String
We can use the String lastIndexOf JavaScript method to get the last position of a value (string or character) within a string. If the value is not found within the string, -1 is returned. "Text".lastIndexOf('x'); This would result in the following output: 2 Some other examples of the lastIndexOf JavaScript method are below: var text […]
Examples Using the JavaScript += Addition Assignment Operator
The JavaScript += addition assignment operator will take the value on the right side of the operator and add it to the value of the variable on the left side of the addition operator. someVaraible += 3; The above code would be the equivalent of: someVaraible = someVaraible + 3; Let’s see a simple example […]
Using JavaScript Math Module to Get Euler’s Constant e
To get the value of Euler’s Constant e in JavaScript, the easiest way is to use the JavaScript math module constant e. Math.E returns the value 2.718281828459045. console.log(Math.E) // Output: 2.718281828459045 In JavaScript, we can easily get the value of e for use in various equations and applications with the JavaScript math module. To get […]
Using JavaScript to Convert a String to Uppercase
In JavaScript, we can convert a string to uppercase by using the JavaScript String toUpperCase() method. "This is Some Text".toUpperCase(); When working with strings, it can be useful to convert a string to uppercase. A lot of the time when comparing strings, you will need to convert them both to either uppercase or lowercase to […]
Using JavaScript to Remove the Last Character From a String
In JavaScript, we can remove the last character from a string easily using the String slice() method. var newString = oldString.slice(0,-1); The code above will return the original string minus the last character. Let’s say we have the following JavaScript: var someString = "This is some example text"; var newString = someString.slice(0,-1); In the above […]
Using JavaScript to Remove the First Character From a String
In JavaScript, we can remove the first character from a string easily using the String substring() method. var newString = oldString.substring(1); The code above will return the original string minus the first character. Let’s say we have the following JavaScript: var someString = "This is some example text"; var newString = someString.substring(1); In the above […]
How to Convert a String to Lowercase In JavaScript
We can convert a String to lowercase in JavaScript easily by using the JavaScript String toLowerCase() method. "This is Some Text".toLowerCase(); When working with strings, it can be useful to convert a string to lowercase. A lot of the time when comparing strings, you will need to convert them both to lowercase to compare them […]
How to Check if a Number is Even or Odd in JavaScript
To tell if a Number in JavaScript is even or odd, we can use the modulus (remainder) operator % along with an if conditional statement. if ((num % 2) == 0){ //Number is Even } else { //Number is Odd } If the remainder of a number after dividing by 2 is 0, then the […]
Remove the Last Element From Array in JavaScript
To remove the last element from an array in JavaScript we can use the Array pop() method. var colors = ["Red", "Green", "Blue", "Orange","Yellow"]; colors.pop(); Let’s take a look at a simple example below. Let’s say we have a simple array of colors and we want to remove the last color from the array. To […]
Remove the First Element From Array in JavaScript
To remove the first element from an array in JavaScript we can use the Array shift() method. var colors = ["Red", "Green", "Blue", "Orange","Yellow"]; colors.shift(); Let’s take a look at a simple example below. Let’s say we have a simple array of colors and we want to remove the first color from the array. To […]
Using JavaScript to get the Last Element in Array
In JavaScript, to get the last element in an array we can do this simply by using the length property. var lastElement = someArray[someArray.length-1] In the above code, someArray is our array, and to get the last element in it, we have to get the length of the array. We also have to subtract 1 […]
Using JavaScript to Rotate an Image
We can use JavaScript to rotate an image easily by targeting the Style transform property and using the getElementById() method. document.getElementById("image1").style.transform = "rotate(20deg)"; In the code above, you can change “20deg” to any degree amount you want to rotate the image by. Let’s say we have the following HTML: <div id="div1"> <img id="image1" src="http://theprogrammingexpert.com/wp-content/uploads/example-img1.png"> </div> […]
JavaScript onkeydown – How to Use onkeydown Event with JavaScript
We can use the onkeydown event to run a function when a user types something into an input field. To do this we can add a function call to the onkeydown event in the HTML. <input type="text" /> The onkeydown event is very similar to the onkeyup event, the main difference being that the onkeydown […]
JavaScript onkeyup – How to Use onkeyup Event with JavaScript
We can use the onkeyup event to run a function when a user types something into an input field. To do this we can add a function call to the onkeyup event in the HTML. <input type="text" onkeyup="funct1()"> The onkeyup event is very similar to the onkeydown event, the main difference being that the onkeydown […]
Using JavaScript to Get the Min Value in an Array
In JavaScript, to get the min value in an array we can do this by using a for loop with an if conditional statement. Here is a function to get the min number of an array. function getMinNum(){ var minNumber = arrayOfNumber[0]; for (var i = 0; i < arrayOfNumber.length; i++) { if( arrayOfNumber[i] < […]
Using JavaScript to Get the Max Value in an Array
In JavaScript, to get the max value in an array we can do this by using a for loop with an if conditional statement. Here is a function to get the max number of an array. function getMaxNum(){ var maxNumber = arrayOfNumber[0]; for (var i = 0; i < arrayOfNumber.length; i++) { if( arrayOfNumber[i] > […]
How to Iterate through an Array Using JavaScript
To iterate through an array using JavaScript we can use a for loop. Here is a simple setup of how to use a for loop to iterate through an array: for (var i = 0; i < someArray.length; i++) { //Do something with array "someArray" } Let’s take a look at a simple example below. […]
Using the getElementsByClassName Method in JavaScript
To get multiple HTML elements using JavaScript, we can use the getElementsByClassName() method if all the elements share the same classname. document.getElementsByClassName("classes") The getElementsByClassName() method will return a collection of HTML elements. In this case, it will be HTML elements with the class name of “classes”. Let’s say I have the following HTML: <div id="div1"> […]
Finding the Length of a String in JavaScript
To find the length of a String in JavaScript we can use the JavaScript String length property. The length property will return the length of the string, and if the string is empty, it will return 0. var stringLength = "This is a String".length; The above code would return the number 16. Some other examples […]
Using JavaScript to Get a Random Number Between Range of Numbers
To get a random number between a range of numbers using JavaScript, we first need to know how to generate a random number. To generate a random number using JavaScript, the simplest way is to use the JavaScript random() method: var random = Math.random(); The Javascript Math random() method generates a number between 0 and […]
charAt() JavaScript – Getting the Index Position of a Character
We can use the String charAt() JavaScript method to get the character of a string at a given index. If the given index is not valid, an empty string is returned. "Text".charAt(0); This would result in the following output: T Some other examples of the charAt() method are below: var text = "Example text"; var […]
How to Count Vowels in a String Using JavaScript
We can count the vowels in a String in JavaScript by using the JavaScript match() method, the length property, and a regex expression. someString.match(/[aeiou]/gi).length; Not that the formula above works great as long as there is a vowel in the string. However, if there is no vowel in the string, the expressions will return an […]
Using the appendChild Method with JavaScript to Add Items to a List
We can use the appendChild method and JavaScript to add a node to the end of another node. document.getElementById("list").appendChild(node); In the code above, appendChild() takes a node and will add it to the end of a list of nodes that we have. We can create a new node using the Document createElement() method. Let’s take […]
JavaScript Trig – How to Use Trigonometric Functions in Javascript
In JavaScript, we can easily do trigonometry with the many trig functions from the JavaScript math module. In this article, you will learn about all the trigonometric functions that you can use in JavaScript to perform trigonometry easily. In JavaScript, we can easily use trigonometric functions with the JavaScript math module. The JavaScript math module […]
JavaScript value – Get the Value from an Input Field
To get the value from an input field, we can use the value property. We can also use the value property to set the value of an input field. var userInput = document.getElementById("input1").value; Let’s say we have the following HTML: <form> <label for="fname">Full Name:</label> <input type="text" id="fname" name="fname"> <button type="submit" value="Submit">Submit</button> </form> To get the […]
How to Convert Degrees to Radians Using JavaScript
To convert degrees to radians using JavaScript, you need to multiply the degrees by pi and divide by 180. Below is a function which will convert degrees to radians for you in JavaScript. function degrees_to_radians(degrees) { return degrees * (Math.PI / 180); } Converting degrees to radians involves the application of a very easy formula. […]
How to Convert Radians to Degrees Using JavaScript
To convert radians to degrees using JavaScript, you need to multiply the radians by 180 and divide by pi. Below is a function which will convert radians to degrees for you in JavaScript. function radians_to_degrees(radians) { return radians * (180 / Math.PI); } Converting radians to degrees involves the application of a very easy formula. […]
JavaScript Exponent – Exponentiate Numbers with Math.pow()
In JavaScript, to get the value of a number and its exponent, we can use the Math.pow() method. var num = Math.pow(2,4); The output of the code above would be the number 16. Some other examples of Math.pow() method are below: var num1 = Math.pow(6,1); var num2 = Math.pow(2,2); var num3 = Math.pow(3,25); var num4 […]
Using JavaScript to Replace Space With Dash
To replace a space with a dash in a paragraph using JavaScript, we can use the JavaScript String replace() method. text.replace(/ /g, '-'); Let’s say we have the following HTML: <div id="div1"> <p id="p1">We will update the text: <span id="span1">up to date</span></p> </div> If we want to change the spaces in the span “up to […]
How to Use JavaScript to Check if a String is Empty
We can check if a string is empty by using an if else conditional statement, and then use JavaScript to do something with this information. This is our preferred method to use. var someString = ""; if (someString) { // The string is NOT empty } else { // The string IS empty } You […]
Using JavaScript to Subtract Days From a Date
To subtract days from a date, we can use the JavaScript getTime() method. The getTime() method converts dates into the number of milliseconds since January 1st, 1970. Since there are 86400000 milliseconds in 1 day, we can subtract multiples of 86400000 to our converted date to subtract as many days as we want. var date1 […]
Using JavaScript to Change the href of a Link
To change the href of a link using JavaScript, we can use the href property along with the getElementById method. document.getElementById("link1").href = "some-url.html"; Let’s say I have the following HTML code: <div id="div1"> <a id="link1" href="http://theprogrammingexpert.com/">Home Page</a> </div> To change the href of #link1 from http://theprogrammingexpert.com/ to http://theprogrammingexpert.com/category/javascript/, we will use the href property in […]
Using JavaScript to Change the Image src
To change the src of an image using JavaScript, we simply use the image src property along with the getElementById method. document.getElementById("img1").src = "anotherImg.jpg"; Let’s say I have the following HTML code: <div id="div1"> <img id="img1" src="img.jpg"> </div> To change the image src of #img1 from img.jpg to anotherImg.jpg, we will use the src property […]
Get the First Child Element and Change it with JavaScript
To get the first child of an HTML element, we can use the firstElementChild property and use JavaScript to make changes to that element. document.getElementById("div1").firstElementChild; Let’s say we have the following HTML: <div id="div1"> <p>This is the first child of #div1</p> <p>This is the second child of #div1</p> <p>This is the third child of #div1</p> […]
Using JavaScript to Change the Font Size of a Paragraph
To change the font size of a paragraph using JavaScript, we simply use the style fontSize property. document.getElementById("p1").style.fontSize = "12px"; Let’s say we have the following HTML: <div id="div1"> <p id="p1">We will change the font size of this text.</p> </div> If we want to change the font size of the paragraph to “12px”, we will […]
JavaScript Change Text Color of a Paragraph
To change the text color of a paragraph using JavaScript, we simply use the Style color property. document.getElementById("div1").style.color = "green"; Let’s say we have the following HTML: <div id="div1"> <p id="p1">We will change the color of this text.</p> </div> If we want to change the color of the paragraph to green, we will use the […]
How to Use JavaScript to Change Button Text
To change button text using JavaScript, the simplest way is to use the textContent property along with the getElementById method. document.getElementById("button").textContent="Submit"; You can also use the innerHTML property to change button text. document.getElementById("button").innerHTML = "Submit"; Let’s say I have the following HTML form: <form action="/action_page.php" method="get" id="form1"> <label for="firstname">First Name:</label> <input type="text" id="fname" name="firstname"> <label […]
JavaScript toLocaleString – Display the Date and Time Using JavaScript
The JavaScript toLocaleString method will take a date object and return the date as a string using the local settings from your computer. var currDate = new Date(); var localDate = currDate.toLocaleString(); The date is returned in a much friendlier format for the user than what the Date() method returns. The outputs of currDate and […]
pi JavaScript – Get Value of pi from JavaScript Math Module
To get the value of pi in JavaScript, the easiest way is use the JavaScript math module constant pi. Math.PI returns the value 3.141592653589793. console.log(Math.PI) //Output: 3.141592653589793 In JavaScript, we can easily get the value of pi for use in trigonometry with the JavaScript math module. For example, let’s say we want to find the […]
JavaScript atanh – Find Hyperbolic Arctangent of Number
To find the hyperbolic arctangent of a number, we can use the JavaScript atanh() function from the math module. Math.atanh(x) In JavaScript, we can easily use trigonometric functions with the Python math module. The JavaScript math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to the hyperbolic […]
JavaScript acosh – Find Hyperbolic Arccosine of Number
To find the hyperbolic arccosine of a number, we can use the JavaScript acosh() function from the math module. Math.acosh(x) In JavaScript, we can easily use trigonometric functions with the Python math module. The JavaScript math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to the hyperbolic […]
JavaScript asinh – Find Hyperbolic Arcsine of Number Using Math.asinh()
To find the hyperbolic arcsine of a number, we can use the JavaScript asinh() function from the math module. Math.asinh(x) In JavaScript, we can easily use trigonometric functions with the Python math module. The JavaScript math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to the hyperbolic […]
JavaScript tanh – Find Hyperbolic Tangent of Number Using Math.tanh()
To find the hyperbolic tangent of a number, we can use the JavaScript tanh() function from the math module. Math.tanh(x) In JavaScript, we can easily use trigonometric functions with the Python math module. The JavaScript math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to the hyperbolic […]
JavaScript cosh – Find Hyperbolic Cosine of Number Using Math.cosh()
To find the hyperbolic cosine of a number, we can use the JavaScript cosh() function from the math module. Math.cosh(x) In JavaScript, we can easily use trigonometric functions with the Python math module. The JavaScript math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to the hyperbolic […]
JavaScript sinh – Find Hyperbolic Sine of Number Using Math.sinh()
To find the hyperbolic sine of a number, we can use the JavaScript sinh() function from the math module. Math.sinh(x) In JavaScript, we can easily use trigonometric functions with the Python math module. The JavaScript math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to the hyperbolic […]
JavaScript atan2 – Find Arctangent of the Quotient of Two Numbers
To find the arctangent, or inverse tangent, of the quotient of two numbers, we can use the JavaScript atan2() function from the math module. Math.atan2(x,y) In JavaScript, we can easily use trigonometric functions with the JavaScript math module. The JavaScript math module allows us to perform trigonometry easily. With the JavaScript math module, we can […]
JavaScript atan – Find Arctangent and Inverse Tangent of Number
To find the arctangent, or inverse tangent, of a number, we can use the JavaScript atan() function from the math module. Math.atan(x) In JavaScript, we can easily use trigonometric functions with the JavaScript math module. The JavaScript math module allows us to perform trigonometry easily. With the JavaScript math module, we can find the arctangent […]
JavaScript acos – Find Arccosine and Inverse Cosine of Number
To find the arccosine, or inverse cosine, of a number, we can use the JavaScript acos() function from the math module. Math.acos(x) In JavaScript, we can easily use trigonometric functions with the JavaScript math module. The JavaScript math module allows us to perform trigonometry easily. With the JavaScript math module, we can find the arccosine […]
JavaScript asin – Find Arcsine and Inverse Sine of Number
To find the arcsine, or inverse sine, of a number, we can use the JavaScript asin() function from the math module. Math.asin(x) In JavaScript, we can easily use trigonometric functions with the JavaScript math module. The JavaScript math module allows us to perform trigonometry easily. With the JavaScript math module, we can find the arcsine […]
JavaScript tan – Find Tangent of Number in Radians Using Math.tan()
To find the tangent of a number (in radians), we can use the JavaScript tan() function from the math module. Math.tan(x) In JavaScript, we can easily use trigonometric functions with the JavaScript math module. The JavaScript math module allows us to perform trigonometry easily. With the JavaScript math module, we can find the tangent of […]
JavaScript cos – Find Cosine of Number in Radians Using Math.cos()
To find the cosine of a number (in radians), we can use the JavaScript cos() function from the math module. Math.cos(x) In JavaScript, we can easily use trigonometric functions with the JavaScript math module. The JavaScript math module allows us to perform trigonometry easily. With the JavaScript math module, we can find the cosine of […]
JavaScript sin – Find Sine of Number in Radians Using Math.sin()
To find the sine of a number (in radians), we can use the JavaScript sin() function from the math module. Math.sin(x) In JavaScript, we can easily use trigonometric functions with the JavaScript math module. The JavaScript math module allows us to perform trigonometry easily. With the JavaScript math module, we can find the sine of […]
JavaScript slice – How to Get a Substring From a String
To get a substring from a string we can use the JavaScript slice method. var newText = "Text".slice(0,3); This would result in the following output: Tex Some other examples of the slice() method are below: var text = "Example text"; var str1 = text.slice(0,3); var str2 = text.slice(1,4); var str3 = text.slice(3); var str4 = […]
Using JavaScript to Get the Current URL
To get the URL of the current page we are on, we can use the JavaScript window.location object and get the href property of it. So the property window.location.href would return the current URL that you see at the top of your browser. var currURL = window.location.href; As we will see in the example below, […]
JavaScript Map Size – Find Length of JavaScript Map
In JavaScript, we can easily find the size of a map using the map size property on a map object. map.size; In JavaScript, the map object is useful for holding key-value pairs. When working with objects in JavaScript, the ability to get the size or length of an object can be useful for use in […]
JavaScript Sorted Map – How to Sort a Map by Keys or Values
With JavaScript, we can easily sort a map by keys or get a sorted map by values using the JavaScript sort() function. sorted_map_by_keys = new Map([…map_to_sort].sort((a, b) => String(a[0]).localeCompare(b[0]))) sorted_map_by_num_values = new Map([…map_to_sort].sort((a, b) => a[1] – b[1])) sorted_map_by_str_values = new Map([…map_to_sort].sort((a, b) => String(a[1]).localeCompare(b[1]))) In JavaScript, the map object is useful for holding key-value […]
parseFloat JavaScript – How to use the JavaScript parseFloat() method
The parseFloat JavaScript method will parse the value given to it as a string and then return the first number in the string. This is done using the parseFloat() method. var num = parseFloat("20"); The above code would return the number 20. Some other examples of the parseFloat() method are below: var num1 = parseFloat(1); […]
Add Years to a Date Using JavaScript
To add years to a date, we can use the JavaScript getFullYear() method. The getFullYear() method gets the current year of a date object. We can then add more years to it and create a new Date using the Date() method. var date1 = new Date(); var currYear = date1.getFullYear(); var currMonth = date1.getMonth(); var […]
Add Days to a Date Using JavaScript
To add days to a date, we can use the JavaScript getTime() method. The getTime() method converts dates into the number of milliseconds since January 1st, 1970. Since there are 86400000 milliseconds in 1 day, we can add multiples of 86400000 to our converted date to add as many days as we want. var date1 […]
Add Hours to a Date Using JavaScript
To add hours to a date, we can use the JavaScript getTime() method. The getTime() method converts dates into the number of milliseconds since January 1st, 1970. Since there are 3600000 milliseconds in 1 hour, we can add multiples of 3600000 to our converted date to add as many hours as we want. var date1 […]
Add Minutes to a Date Using JavaScript
To add minutes to a date, we can use the JavaScript getTime() method. The getTime() method converts dates into the number of milliseconds since January 1st, 1970. Since there are 60000 milliseconds in 1 minute, we can add multiples of 60000 to our converted date to add as many minutes as we want. var date1 […]
JavaScript Change Border Color of Element
We can use JavaScript to change the border color of a div using the borderColor property. document.getElementById("div1").style.borderColor = "green"; Let’s say we have the following HTML: <div id="div1"> <p>We want to change the border color of the containing div.</p> </div> If we want to change the border color of #div1 to green, we can use […]
How to Call a JavaScript Function From HTML
To call a JavaScript function from HTML, we can add an onclick event in our HTML code that will fire a function when the HTML element is clicked on. <div id="div1" onclick="funct1()">Click me to run the function funct1</div> We can also use the onmouseover event to call a function when the user moves a mouse […]
Using JavaScript to Get the Current Year
We can use JavaScript to get the current year using the getFullYear() method. It will return the year in a four-digit format. var currDate = new Date(); var currYear = currDate.getFullYear(); The value of currYear in the code above would return the current year. The day this post was written was January 16th, 2022, so […]
Using JavaScript to Get the Current Month
One of the easiest ways we have found to use JavaScript to get the current month is to make use of the JavaScript toLocaleString() method. We can simply change a couple parameters of the method to easily get the month in any format we want. The toLocaleString() method has the following options for the month […]
getDate JavaScript – Get the Current Day of the Month in JavaScript
The getDate JavaScript method will get the current day of the month from a date object using the getDate() method. It will return a number from 1 to 31. var currDate = new Date(); var currDay = currDate.getDate(); The value of currDay in the code above would return whatever the day of the month it […]
JavaScript Random Number – How to Generate a Random Number In JavaScript
To generate a random number using JavaScript, the simplest way is to use the JavaScript random() method: var random = Math.random(); Random number generation with JavaScript is easy to do. All we need is the Javascript Math random() method. The Javascript Math random() method generates a number between 0 and 1 (including 0 and excluding […]
Math abs JavaScript – How to get the absolute value of a number using JavaScript
To get the absolute value of a number we can use the Math abs JavaScript method, Math.abs(). var num = Math.abs(-7); The above code would return the number 7. Some other examples of Math.abs() are below: var num = Math.abs(7); var num1 = Math.abs(.6789); var num2 = Math.abs(0); var num3 = Math.abs(-50); var num4 = […]
JavaScript Trunc with Math.trunc() Method
The JavaScript trunc method will remove the decimals of a number and return just the integer, using the Math.trunc() method. var num = Math.trunc(9.31); The above code would return the number 9. Some other examples of Math.trunc() are below: var num = Math.trunc(1.123); var num1 = Math.trunc(.6789); var num2 = Math.trunc(1020.12); var num3 = Math.trunc(-.54); […]
JavaScript Square Root with Math.sqrt() Method
In JavaScript, to get the square root of a number we use the Math.sqrt() method. var num = Math.sqrt(9); The above code would return the number 3. Some other examples of Math.sqrt() are below: var num = Math.sqrt(1); var num1 = Math.sqrt(0); var num2 = Math.sqrt(10); var num3 = Math.sqrt(196); var num4 = Math.sqrt(31.3); var […]
Using JavaScript to Disable a Button
We can use JavaScript to disable a submit button on a form. The easiest way to do this is by using the disabled property. document.getElementById("button1").disabled = true; Here we can use the disabled property of the button input, and change its disabled property to true. An example of using JavaScript to enable/disable a button on […]
JavaScript indexOf – Get the position of a value within a string
We can use the JavaScript indexOf method to get the starting position of a value (String or character) within a string. If the value is not found within the string, -1 is returned. "Text".indexOf('x'); This would result in the following output: 2 Some other examples of the indexOf() method are below: var text = "Example […]
JavaScript substring – How to Get a Substring From a String
To get a substring from a string in JavaScript, we can use the substring() method. "Text".substring(0,3); This would result in the following output: Tex Some other examples of the substring() method are below: var text = "Example text"; var str1 = text.substring(0,3); var str2 = text.substring(1,4); var str3 = text.substring(3); var str4 = text.substring(3,0); var […]
JavaScript Ceiling – Using Math.ceil() Method to Round Up to Ceiling
The JavaScript ceiling method will take a number and round it UP to the nearest integer. This is done using the Math.ceil() method. var num = Math.ceil(1.6); The above code would round the number 1.6 UP to 2. Some other examples of Math.ceil() are below: var num = Math.ceil(1.6); var num1 = Math.ceil(.6); var num2 […]
Math floor JavaScript – Using Math.floor() to Round Down to Floor
The Math floor JavaScript method will take a number and round it DOWN to the nearest integer. This is done using the Math.floor() method. var num = Math.floor(1.6); The above code would round the number 1.6 DOWN to 1. Some other examples of Math.floor() are below: var num = Math.floor(1.6); var num1 = Math.floor(.6); var […]
How to Use JavaScript to Change Text in Span
There are a couple of ways that we can change the text in a span using JavaScript. The first way we can do this is with the innerHTML property: document.getElementById("div1").innerHTML = "Changing <span>this text</span> in #div1"; Let’s say we have the following HTML: <div> <div id="div1">Today is <span>November</span> 3rd.</div> </div> The innerHTML property gives us […]
Using JavaScript to Change Text of Element
To change the text in a div using JavaScript, we can use the textContent property: document.getElementById("div1").textContent="newContent"; If your div will contain html content, then you should use the innerHTML property. document.getElementById("div1").innerHTML = "<span>Paragraph changed!</span>"; Let’s say we have the following HTML: <div id="div1">Today is November 3rd.</div> If we want to change the text inside the […]
JavaScript Change Background Color of Element
Changing the background color of a div using JavaScript is done simply by using the backgroundColor property. document.getElementById("div1").style.backgroundColor = "green"; Let’s say we have the following HTML: <div id="div1"> <p>This paragraph is in a div that we need to change the color of.</p> </div> If we want to change the background color of #div1 to […]
Using Javascript to Remove Class from Element
To remove a class from an HTML element using Javascript, the simplest way is to get the classList of the element and then use the remove() method. document.getElementById("div1").classList.remove("old-class"); Let’s say I have the following HTML: <div id="div1" class="existing-class"> <p class="p">This is a paragraph.</p> </div> If we want to remove the class “existing-class” from #div1, we […]
Using Javascript to Add Class to Element
To add a class to an HTML element using Javascript, the simplest way is to get the classList of the element and then use the add() method. document.getElementById("div1").classList.add("new-class"); Let’s say I have the following HTML: <div id="div1" class="existing-class"> <p class="p">This is a paragraph.</p> </div> If we want to add the class “new-class” to #div1, we […]
React Axios Interceptor to Prevent Infinite Loops in JWT Authentication
Dynamic web applications are very popular these days, and many web applications need to have some sort of user management to be able to best serve the app users. One popular frontend and backend combination is using React (Javascript) on the frontend and Django (Python) on the backend. There are many different ways to do […]
Grouping By Multiple Properties and Summing Using Javascript
When processing data, it is very useful to be able to group by variables and calculate statistics for each group. In Javascript, we can use the reduce function to help us build a group by function. Grouping Objects by Multiple Properties in Array in Javascript Let’s say we have data such as the following: var […]
How to Filter a List of Divs with a Text Input Bar Using Javascript
Being able to add filtering functionality to lists using Javascript and jQuery can be very beneficial for the user experience of a web page. It is very common for a page to have a list of products, events, blogs, etc. which the user could want to sort or filter – depending on the purpose of […]
Sort List of Divs with Data Attribute with Radio Buttons Using Javascript
We can use Javascript and jQuery to sort a list of divs very easily by using the sort() Javascript function. Being able to add sorting functionality to lists using Javascript and jQuery can be very beneficial for the user experience of a web page. It is very common for a page to have a list […]