Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Object Oriented Programming Articles
Page 129 of 589
How can I cut a string after X characters in JavaScript?
To cut a string after X characters in JavaScript, you can use several methods. The most common approaches are substr(), substring(), and slice(). Using substr() Method The substr() method extracts a portion of a string, starting at a specified index and extending for a given number of characters. var myName = "JohnSmithMITUS"; console.log("The String = " + myName); var afterXCharacter = myName.substr(0, 9); console.log("After cutting the characters the string = " + afterXCharacter); The String = JohnSmithMITUS After cutting the characters the string = JohnSmith Using substring() Method The substring() ...
Read MoreHow to set attribute in loop from array JavaScript?
Let's say we are required to write a function that takes in an array and changes the id attribute of first n divs present in a particular DOM according to corresponding values of this array, where n is the length of the array. We will first select all divs present in our DOM, iterate over the array we accepted as one and only argument and assign the corresponding id to each div. Basic Example Here's the HTML structure we'll work with: Setting Attributes in Loop ...
Read MoreWhy does Array.map(Number) convert empty spaces to zeros? JavaScript
When using Array.map(Number) on a string containing spaces, JavaScript converts empty spaces to zeros. This happens due to how the Number() constructor handles string-to-number conversion. The Problem Let's examine this behavior with a practical example: const digify = (str) => { const parsedStr = [...str].map(Number) return parsedStr; } console.log(digify("778 858 7577")); [ 7, 7, 8, 0, 8, 5, 8, 0, 7, 5, 7, 7 ] Notice how the spaces in the string are converted to 0 instead ...
Read MoreAvoid Unexpected string concatenation in JavaScript?
JavaScript string concatenation can lead to unexpected results when mixing strings and numbers. Using template literals with backticks provides a cleaner, more predictable approach than traditional concatenation methods. The Problem with Traditional Concatenation When using the + operator, JavaScript may perform string concatenation instead of numeric addition: let name = "John"; let age = 25; let score = 10; // Unexpected string concatenation console.log("Age: " + age + score); // "Age: 2510" (not 35!) console.log(name + " is " + age + " years old"); Age: 2510 John is 25 years ...
Read MoreClearing localStorage in JavaScript?
localStorage is a web storage API that persists data in the browser until explicitly cleared. Here are two effective methods to clear localStorage in JavaScript. Method 1: Using clear() Method The clear() method removes all key-value pairs from localStorage at once. This is the most efficient approach. // Store some data first localStorage.setItem("name", "John"); localStorage.setItem("age", "25"); localStorage.setItem("city", "New York"); console.log("Before clearing:", localStorage.length); // Clear all localStorage localStorage.clear(); console.log("After clearing:", localStorage.length); Before clearing: 3 After clearing: 0 Method 2: ...
Read MoreDisplay array items on a div element on click of button using vanilla JavaScript
To display array items in a div element when a button is clicked, we need to iterate through the array and append each element to the target div. This is commonly done using JavaScript's forEach() method or a simple loop. Basic Approach The core concept involves selecting the target div using getElementById() and updating its innerHTML property with array elements: const myArray = ["stone", "paper", "scissors"]; const embedElements = () => { myArray.forEach(element => { document.getElementById('result').innerHTML += ...
Read MoreFiltering of JavaScript object
Filtering JavaScript objects allows you to extract specific key-value pairs based on certain criteria. This is useful when working with large datasets or when you need to display only relevant information. Problem Statement We need to create a function that takes an object and a search string, then filters the object keys that start with the search string and returns a new filtered object. Example: Basic Object Filtering const obj = { "PHY": "Physics", "MAT": "Mathematics", "BIO": "Biology", "COM": "Computer Science", "SST": "Social Studies", ...
Read MoreReverse a number in JavaScript
Our aim is to write a JavaScript function that takes in a number and returns its reversed number. For example, reverse of 678 is: 876 There are multiple approaches to reverse a number in JavaScript. Let's explore the most common methods. Method 1: Using String Conversion The most straightforward approach converts the number to a string, reverses it, and converts back to a number: const num = 124323; const reverse = (num) => parseInt(String(num) .split("") .reverse() .join(""), 10); console.log(reverse(num)); ...
Read MoreSeparate a string with a special character sequence into a pair of substrings in JavaScript?
When you have a string containing a special character sequence that acts as a delimiter, you can separate it into substrings using JavaScript's split() method with regular expressions. Problem Statement Consider this string with a special character sequence: " John Smith " We need to split this string at the delimiter and get clean substrings without extra whitespace. Syntax var regex = /\s*\s*/g; var result = string.trim().split(regex); Example var fullName = " John Smith "; console.log("Original string: " + fullName); var regularExpression = ...
Read MoreCombine unique items of an array of arrays while summing values - JavaScript
We have an array of arrays, where each subarray contains exactly two elements: a string (person name) and an integer (value). Our goal is to combine subarrays with the same first element and sum their second elements. For example, this input array: const example = [ ['first', 12], ['second', 19], ['first', 7] ]; Should be converted to: [ ['first', 19], ['second', 19] ] Solution Using Object Mapping We'll create ...
Read More