javascript

How to Remove All Whitespace from a String in JavaScript

To remove all whitespace from a string in JavaScript, call the replace() method on the string, passing a regular expression that matches any whitespace character, and an empty string as a replacement. For example, str.replace(/\s/g, '') returns a new string with all whitespace removed from str.

const str = '1 2 3';

const whitespaceRemoved = str.replace(/\s/g, '');
console.log(whitespaceRemoved); // 123

The \s regex metacharacter matches whitespace characters, such as spaces, tabs, and newlines.

We use the g regex flag to specify that all whitespace characters in the string should be matched. Without this flag, only the first whitespace will be matched and replaced:

const str = '1 2 3';

// No 'g' flag in regex
const whitespaceRemoved = str.replace(/\s/, '');

// Only first whitespace removed
console.log(whitespaceRemoved); // 12 3

The replace() method returns a new string with all the matches replaced with the second argument passed to it. We pass an empty string ('') as the second argument to replace all the whitespace with nothing, which effectively removes them.

Note

replace() returns a new string without modifying the original string, as strings in JavaScript are immutable.

const str = '1 2 3';
const whitespaceRemoved = str.replace(/\s/g, '');

console.log(whitespaceRemoved); // 123

// Not modified
console.log(str); // 1 2 3

How to Find the Odd Numbers in an Array with JavaScript

In this article, we’ll be looking at different ways to find the odd numbers in an array using JavaScript.

1. Array filter() Method

To find the odd numbers in an array, we can call the Array filter() method, passing a callback that returns true when the number is odd, and false otherwise.

const numbers = [8, 19, 5, 6, 14, 9, 13];

const odds = numbers.filter((num) => num % 2 === 1);
console.log(odds); // [19, 5 , 9, 13]

The filter() method creates a new array with all the elements that pass the test specified in the testing callback function. So, filter() returns an array of all the odd numbers in the original array.

2. Array forEach() Method

Another way to find the odd numbers in a JavaScript array is with the Array forEach() method. We call forEach() on the array, and in the callback, we only add an element to the resulting array if it is odd. For example:

const numbers = [8, 19, 5, 6, 14, 9, 13];

const odds = [];
numbers.forEach((num) => {
  if (num % 2 === 1) {
    odds.push(num);
  }
});

console.log(odds); // [19, 5, 9, 13]

3. for…of Loop

We can use the for...of loop in place of forEach() to iterate through the array:

const numbers = [8, 19, 5, 6, 14, 9, 13];

const odds = [];
for (const num of numbers) {
  if (num % 2 === 1) {
    odds.push(num);
  }
}
console.log(odds); // [19, 5, 9, 13]

How to Check if a String Contains a Substring in JavaScript

In this article, we look at multiple ways to quickly check if a string contains a substring in JavaScript.

1. String includes() Method

To check if a string contains a substring, we can call the includes() method on the string, passing the substring as an argument e.g., str.includes(substr). The includes() method returns true if the string contains the substring, otherwise, it returns false.

const str = 'Bread and Milk';

const substr1 = 'Milk';
const substr2 = 'Tea';

console.log(str.includes(substr1)); // true

console.log(str.includes(substr2)); // false

Tip

To perform a case-insensitive check, convert both the string and the substring to lowercase before calling includes() on the string.

const str = 'Bread and Milk';

const substr = 'milk';

console.log(
  str.toLowerCase().includes(substr.toLowerCase())
); // true

2. String indexOf() Method

We can also use the indexOf() method to check if a string contains a substring. We call the indexOf() method on the string, passing the substring as an argument. Then we compare the result with -1. For example:

const str = 'Bread and Milk';

const substr1 = 'Milk';
const substr2 = 'Tea';

console.log(str.indexOf(substr1) > -1); // true

console.log(str.indexOf(substr2) > -1); // false

The indexOf() method searches a string for a value and returns the index of the first occurrence of that value. If the value can’t be found, it returns -1.

const str = 'Bread and Milk';

const substr1 = 'Milk';
const substr2 = 'Tea';

console.log(str.indexOf(substr1)); // 10
console.log(str.indexOf(substr2)); // -1

This is why we compare the result of indexOf() with -1 to check if the substring is in the string.

Tip

To perform a case-insensitive check, convert both the string and the substring to lowercase before calling indexOf() on the string.

const str = 'Bread and Milk';

const substr = 'milk';

console.log(
  str.toLowerCase().indexOf(substr.toLowerCase()) > -1
); // true

3. Regex Matching

We can test the string against regex patterns to determine if it contains a substring. One way to do this is using the RegExp test() method.

const str = 'Bread and Milk';

console.log(/Milk/.test(str)); // true
console.log(/Tea/.test(str)); // false

Using regex matching allows us to easily specify complex patterns to search the string for.

const str = 'Bread and Milk';

// Contains 'sand', 'land', or 'and'?
console.log(/[sl]?and/.test(str)); // true

// Contains 'book0', 'book1', ..., 'book8' or 'book9'?
console.log(/book(\d)/.test(str)); // false

Check if a String Contains Special Characters in JavaScript

In this article, we’ll be looking at some ways to easily check if a string contains special characters in JavaScript.

1. RegExp test() Method

To check if a string contains special characters in JavaScript, we can test the string against a regular expression that matches any special character. We can use the RegExp test() method for this:

function containsSpecialChars(str) {
  const specialChars =
    /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
  return specialChars.test(str);
}

console.log(containsSpecialChars('book_club')); // true
console.log(containsSpecialChars('milk')); // false
console.log(containsSpecialChars('2 + 3 = 5')); // true

// Usage in if statement
if (containsSpecialChars('book_club')) {
  console.log('Special characters found.');
} else {
  console.log('No special characters found.');
}

The test() method searches a string for a match with a regular expression. It returns true if it finds a match, otherwise, it returns false.

2. Array some() method

Another way to check if a string contains special characters is with the Array some() method:

function containsSpecialChars(str) {
  const specialChars =
    '[`!@#$%^&*()_+-=[]{};\':"\\|,.<>/?~]/';
  return specialChars
    .split('')
    .some((specialChar) => str.includes(specialChar));
}

console.log(containsSpecialChars('book_club')); // true
console.log(containsSpecialChars('milk')); // false
console.log(containsSpecialChars('2 + 3 = 5')); // true

// Usage in if statement
if (containsSpecialChars('book_club')) {
  console.log('Special characters found.');
} else {
  console.log('No special characters found.');
}

First, we create a string containing all the special characters. Notice we have to use a backslash escape (\) to include the single quote (') in the single-quoted string.

Then we call the String split() method, passing an empty string ('') as an argument, to split the string into an array of all the special characters.

/** [
  '[', '`', '!', '@',  '#', '$', '%',
  '^', '&', '*', '(',  ')', '_', '+',
  '-', '=', '[', ']',  '{', '}', ';',
  "'", ':', '"', '\\', '|', ',', '.',
  '<', '>', '/', '?',  '~', ']', '/'
] */
const specialChars =
  '[`!@#$%^&*()_+-=[]{};\':"\\|,.<>/?~]/';
console.log(specialChars.split(''));

The Array some() method tests whether any element of an array satisfied a condition specified in the testing callback function. It returns true if there is at least one element in the array that passes the test. Otherwise, it returns false.

In our example, an element in the array of special characters only passes the test if the string contains the element. So, some() returns true if the string contains at least one special character.

How to Copy to Clipboard in Node.js (Easy Way)

To copy to clipboard in Node.js, you can use the clipboardy package from NPM. First, install it by running the following command at the root of your project directory:

npm i clipboardy

We can use clipboardy to read or write to the system clipboard:

import clipboardy from 'clipboardy';

async function main() {
  await clipboardy.write('butter');
  const text = await clipboardy.read();
  console.log(text); // 'butter'
}

main();

The module can read/write synchronously as well:

import clipboardy from 'clipboardy';

clipboardy.writeSync('butter');

const text = clipboardy.readSync();
console.log(text); // butter

Note

clipboardy is an ES module, and can only be used with the import keyword. The use the import keyword in Node.js, set the the type field to module in your package.json file:

package.json

{
  // ... other fields
  "main": "index.js",
  "type": "module",
  // ... other fields
}

How to Check if a String Contains a Character in JavaScript

In this article, we’ll be looking at different ways to quickly check if a string contains a specific character in JavaScript.

1. String includes() Method

To check if a string contains a particular character, we can call the includes() method on the string, passing the character as an argument e.g., str.includes(char). The includes() method returns true if the string contains the character, and false if it doesn’t.

const str = 'Bread and Milk';

const char1 = 'd';
const char2 = 'p';

console.log(str.includes(char1)); // true

console.log(str.includes(char2)); // false

Tip

To perform a case-insensitive check, convert both the string and the character to lowercase before calling includes() on the string.

const str = 'Bread and Milk';

const char = 'D';

console.log(str.toLowerCase().includes(char.toLowerCase())); // true

2. String indexOf() Method

We can also use the indexOf() method to check if a string contains a particular character. We call the indexOf() method on the string, passing the character as an argument. Then we compare the result with -1. For example:

const str = 'Bread and Milk';

const char1 = 'd';
const char2 = 'p';

console.log(str.indexOf(char1) > -1); // true

console.log(str.indexOf(char2) > -1); // false

The indexOf() method searches a string for a value and returns the index of the first occurrence of that value. If the value can’t be found, it returns -1.

const str = 'Bread and Milk';

const char1 = 'd';
const char2 = 'p';

console.log(str.indexOf(char1)); // 4

console.log(str.indexOf(char2)); // -1

This is why we compare the result of indexOf() with -1 to check if the character is in the string.

3. Regex Matching

We can test the string against regex patterns to determine if it contains a particular character. One way to do this is with the RegExp test() method.

const str = 'Bread and Milk';

console.log(/d/.test(str)); // true

console.log(/p/.test(str)); // false

The test() method searches the string for a match with the regex. It returns true if it finds a match, and false otherwise.

Using regex matching allows us to specify multiple characters to search for in the string easily.

const str = 'Bread and Milk';

// Contains a digit?
console.log(/\d/.test(str)); // false

// Contains 'r', 'l' or 'c'?
console.log(/[rlc]/.test(str)); // true

// Contains whitespace?
console.log(/\s/.test(str)); // true

How to Get an Object Key by Its Value in JavaScript

Object keys() and Array find()

To get the key of an object by value in JavaScript, call the Object.keys() method to get the object keys, then use the find() to find the key associated with the specified value. For example:

function getObjectKey(obj, value) {
  return Object.keys(obj).find((key) => obj[key] === value);
}

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const key = getObjectKey(obj, 'Kate');
console.log(key); // user2

The Object.keys() method takes an object and returns an array of all its keys:

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const keys = Object.keys(obj);
console.log(keys); // [ 'user1', 'user2', 'user3' ]

The Array find() method searches for the element in an array for which a certain condition is true. The condition is specified in the callback testing function passed to find(). The condition we specified only evaluates to true for a key in the array if its corresponding value is equal the value passed to the getObjectKey() function.

Info

If the find() method can’t find any element that satisfies the condition, it returns undefined:

function getObjectKey(obj, value) {
  return Object.keys(obj).find((key) => obj[key] === value);
}

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const key = getObjectKey(obj, 'Sarah');
console.log(key); // undefined

Array filter() vs Array find()

The find() method only returns the first element in the array that satisfies the testing function. If the object containing multiple keys with the same value, it will return only the first key it finds:

function getObjectKey(obj, value) {
  return Object.keys(obj).find((key) => obj[key] === value);
}

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
  user4: 'John',
};

const key = getObjectKey(obj, 'John');
console.log(key); // user1

To get all the keys that correspond to a certain value, you can use the Array filter() method in place of find():

function getObjectKey(obj, value) {
  return Object.keys(obj).filter(
    (key) => obj[key] === value
  );
}

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
  user4: 'John',
};

const key = getObjectKey(obj, 'John');
console.log(key); // ['user1', 'user4']

Unlike find(), filter() returns an array of all the keys with matching values.

How to Get the Last Character of a String in JavaScript

In this article, we’ll be looking at some ways to quickly get the last character of a string in JavaScript.

1. String at() Method

The get the last character of a string, we can call the at() method on the string, passing -1 as an argument. For example, str.at(-1) returns a new string containing the last character of str.

const str = 'Coding Beauty';

const lastChar = str.at(-1);
console.log(lastChar); // y

The String at() method returns the character of a string at the specified index. When negative integers are passed to at(), it counts back from the last string character.

2. String charAt() Method

Alternatively, to get the last character of a string, we can call the charAt() method on the string, passing the last character index as an argument. For example, str.charAt(str.length - 1) returns a new string containing the last character of str.

const str = 'book';

const lastCh = str.charAt(str.length - 1);
console.log(lastCh); // k

The String charAt() method takes an index and returns the character of the string at that index.

Tip

In JavaScript, arrays use zero-based indexing. This means that the first character has an index of 0, and the last character has an index of str.length - 1.

Note

If we pass an index to charAt() that doesn’t exist on the string, it returns an empty string (''):

const str = 'book';

const lastCh = str.charAt(10);
console.log(lastCh); // ''

3. Bracket Notation ([]) Property Access

We can also use the bracket notation ([]) to access the last character of a string. Just like with the charAt() method we use str.length - 1 as an index to access the last character.

const str = 'book';

const lastCh = str[str.length - 1];
console.log(lastCh); // k

Note

Unlike with charAt(), using the bracket notation to access a character at a non-existent index in the string will return undefined:

const str = 'book';

const lastCh = str[10];
console.log(lastCh); // undefined

4. String split() and Array pop() Methods

With this method, we call the split() method on the string to get an array of characters, then we call pop() on this array to get the last character of the string.

const str = 'book';

const lastCh = str.split('').pop();
console.log(lastCh); // k

We passed an empty string ('') to the split() method to split the string into an array of all its characters.

const str = 'book';

console.log(str.split('')); // [ 'b', 'o', 'o', 'k' ]

The Array pop() method removes the last element from an array and returns that element. We call it on the array of characters to get the last character.

[SOLVED] Cannot read property ‘constructor’ of undefined in JS

The “cannot read property ‘constructor’ of undefined” error occurs when you attempt to access the constructor property of a variable that is undefined. To fix it, perform an undefined check on the variable before trying to access the constructor property.

const user = undefined;

// TypeError: Cannot read properties of undefined (reading 'constructor')
const User = user.constructor;
const newUser = new User();

In this example, the user variable is undefined, so we get an error when we try to access a property from it. We fix it by checking if the variable is nullish before accessing the constructor property. We can do this with the optional chaining operator (?.):

const user = undefined;

// Optional chaining in if statement
if (user?.constructor) {
  const User = user?.constructor;
  const newUser = new User();
}

Using the optional chaining operator on a variable will return undefined and prevent the property access if the variable is nullish (null or undefined).

We can also use an if statement to check if the variable is truthy:

const user = undefined;

// Check if 'user' is truthy
if (user && user.constructor) {
  const User = user.constructor;
  const newUser = new User();
}

Tip

In JavaScript, the constructor property of an instance object returns a reference to the Object constructor function that created the object.

let obj1 = {};
obj1.constructor === Object; // -> true

let obj2 = new Object();
obj2.constructor === Object; // -> true

let arr1 = [];
arr1.constructor === Array; // -> true

let arr2 = new Array();
arr2.constructor === Array; // -> true

let num = new Number(3)
num.constructor === Number; // -> true

How to Fix the “Cannot Read Property ‘replace’ of Undefined” Error in JavaScript

Are you experiencing the “cannot read property ‘replace’ of undefined” error in JavaScript? This error occurs when you attempt to call the replace() method on a variable that has a value of undefined.

const str = undefined;

// TypeError: Cannot read properties of undefined (reading 'replace')
const newStr = str.replace('old', 'new');

console.log(newStr);

To fix the “cannot read property ‘replace’ of undefined” error, perform an undefined check on the variable before calling the replace() method on it. There are various ways to do this, and we’ll cover 4 of them in this article.

1. Use an if Statement

We can use an if statement to check if the variable is truthy before calling the replace() method:

const str = undefined;

let result = undefined;
// Check if truthy
if (str) {
  result = str.replace('old', 'new');
}

console.log(result); // undefined

2. Use Optional Chaining

We can use the optional chaining operator (?.) to return undefined and prevent the method call if the variable is nullish (null or undefined):

const str = undefined;

// Optional chaining
const result = str?.replace('old', 'new');

console.log(result); // undefined

3. Call replace() on a Fallback Value

We can use the nullish coalescing operator (??) to provide a fallback value to call replace() on.

const str = undefined;

const result = (str ?? 'old str').replace('old', 'new');

console.log(result); // 'new str'

The null coalescing operator (??) returns the value to its left if it is not null or undefined. If it is, then ?? returns the value to its right.

console.log(5 ?? 10); // 5
console.log(undefined ?? 10); // 10

4. Use a Fallback Result Instead of Calling replace()

We can combine the optional chaining operator (?.) and the nullish coalescing operator (??) to provide a fallback value to use as the result, instead of performing the replacement.

const str = undefined;

const result = str?.replace('old', 'new') ?? 'no matches';

console.log(result); // 'no matches'

Note

If the variable is not nullish but doesn’t have a replace() method, you’ll get a different kind of error:

const obj = {};

// TypeError: obj.replace is not a function
const result = obj.replace('old', 'new');

console.log(result);