Blog

How to Get the First Two Characters of a String in JavaScript

1. String slice() Method

To get the first two characters of a string in JavaScript, call the slice() method on the string, passing 0 and 2 as the first and second arguments respectively. For example, str.slice(0, 2) returns a new string containing the first two characters of str.

const str = 'Coding Beauty';

const firstTwoChars = str.slice(0, 2);
console.log(firstTwoChars); // Co

The String slice() method extracts the part of the string between the start and end indexes, which are specified by the first and second arguments respectively. The substring between the indexes 0 and 2 is a substring containing only the first two string characters.

Note

Strings in JavaScript are immutable, and the slice() method returns a new string without modifying the original:

const str = 'Coding Beauty';

const first2 = str.slice(0, 2);
console.log(first2); // Co

// Original not modified
console.log(str); // Coding Beauty

2. String substring() Method

Alternatively, to get the first two characters of a string, we can call the substring() method on the string, passing 0 and 2 as the first and second arguments respectively. For example, str.substring(0, 2) returns a new string containing the first two characters of str.

const str = 'Coding Beauty';

const firstTwoChars = str.substring(0, 2);
console.log(firstTwoChars); // Co

Like slice(), the substring() method returns the part of a string between the start and end indexes, which are specified by the first and second arguments respectively.

Note

substring() returns a new string without modifying the original:

const str = 'Coding Beauty';

const first2 = str.substring(0, 2);
console.log(first2); // Co

// Original not modified
console.log(str); // Coding Beauty

Tip

The slice() and substring() work similarly for our use case, but this isn’t always so. Here’s one difference between them: substring() swaps its arguments if the first is greater than the second, but slice() returns an empty string ('').

const str = 'Coding Beauty';

const subStr1 = str.substring(2, 0);
const subStr2 = str.slice(2, 0);

// Equivalent to str.substring(0, 2)
console.log(subStr1); // Co

console.log(subStr2); // '' (empty string)

5 Ways to Get the First Character of a String in JavaScript

In this article, we’ll be looking at multiple ways to easily get the first character of a string in JavaScript.

1. String charAt() method

To get the first character of a string, we can call charAt() on the string, passing 0 as an argument. For example, str.charAt(0) returns the first character of str.

JavaScript
const str = 'Coding Beauty'; const firstChar = str.charAt(0); console.log(firstChar); // C

The String charAt() method returns the character of a string at the specified index. The index of the first character is 0.

2. Bracket ([]) notation property access

Alternatively, to get the first character of a string, we can access the 0 property of the string using the bracket notation ([]):

JavaScript
const str = 'Coding Beauty'; const firstChar = str['0']; console.log(firstChar); // C

Bracket notation property access is a useful alternative to dot notation when the property name is an invalid JavaScript identifier. For example, attempting to access the 0 property with dot notation will result in a syntax error, as 0 is not a valid identifier:

JavaScript
const str = 'Coding Beauty'; // SyntaxError: Unexpected number const firstChar = str.0; console.log(firstChar);

Since 0 is a whole number, we don’t need to wrap it in quotes to access it. We can pass a number directly, just like we do with arrays.

JavaScript
const str = 'Coding Beauty'; // Quotes are not needed to pass 0 const firstChar = str[0]; console.log(firstChar); // C

Accessing a property that doesn’t exist returns undefined in JavaScript. So this method is unlike charAt(), which returns an empty string (''):

JavaScript
const str = 'Coding Beauty'; const char1 = str[20]; const char2 = str.charAt(20); console.log(char1); // undefined console.log(char2); // '' (empty string)

3. String substring() method

With this method, we call substring() on the string, passing 0 as the first argument and 1 as the second.

JavaScript
const str = 'Coding Beauty'; const firstChar = str.substring(0, 1); console.log(firstChar); // C

The String substring() method returns the part of a string between the start and end indexes, which are specified by the first and second arguments respectively. The substring between the indexes 0 and 1 is a substring containing only the first string character.

4. String slice() method

With this method, we call slice() on the string, passing 0 as the first argument and 1 as the second.

JavaScript
const str = 'Coding Beauty'; const firstChar = str.slice(0, 1); console.log(firstChar); // C

The String slice() method extracts the part of string between the start and end indexes, which are specified by the first and second arguments respectively. The substring between the indexes 0 and 1 is a substring containing only the first string character.

Note

The slice() and substring() method work similarly for our use case, but this isn’t always so. One of the differences between them is that while substring() swaps its arguments if the first is greater than the second, slice() returns an empty string:

JavaScript
const str = 'Coding Beauty'; const subStr1 = str.substring(6, 0); const subStr2 = str.slice(6, 0); // Equivalent to str.substring(0, 6) console.log(subStr1); // Coding console.log(subStr2); // '' (empty string) 

5. String at() method

Another way to get the first character of a string is with the String at() method, newly added in ES2022. We call at() on the string, passing 0 as an argument.

JavaScript
const str = 'Coding Beauty'; const firstChar = str.at(0); console.log(firstChar); // C

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. This is unlike charAt(), which returns an empty string:

JavaScript
const str = 'Coding Beauty'; const char1 = str.at(-3); const char2 = str.charAt(-3); console.log(char1); // u console.log(char2); // '' (empty string)

How to Remove All Spaces from a String in JavaScript

1. String replaceAll() Method

To remove all spaces from a string in JavaScript, call the replaceAll() method on the string, passing a string containing a space as the first argument and an empty string ('') as the second. For example, str.replaceAll(' ', '') removes all the spaces from str.

const str = 'A B C';
const allSpacesRemoved = str.replaceAll(' ', '');

console.log(allSpacesRemoved); // ABC

The String replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The first argument is the pattern to match, and the second argument is the replacement. So, passing the empty string as the second argument replaces all the spaces with nothing, which removes them.

Note

Strings in JavaScript are immutable, and replaceAll() returns a new string without modifying the original.

const str = 'A B C';
const allSpacesRemoved = str.replaceAll(' ', '');

console.log(allSpacesRemoved); // ABC

// Original not modified
console.log(str); // A B C

2. String replace() Method with Regex

Alternatively, we can remove all spaces from a string by calling the replace() method on the string, passing a regular expression matching any space as the first argument, and an empty string ('') as the second.

const str = 'A B C';
const allSpacesRemoved = str.replace(/ /g, '');

console.log(allSpacesRemoved); // ABC

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

const str = 'A B C';

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

// Only first space removed
console.log(spacesRemoved); // AB C

The String 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 spaces with nothing, which removes them.

Note

As with replaceAll(), replace() returns a new string without modifying the original.

const str = 'A B C';
const spacesRemoved = str.replace(/ /g, '');

console.log(spacesRemoved); // ABC

// Original not modified
console.log(str); // A B C

Tip

The regular expression we specified only matches spaces in the string. To match and remove all whitespace characters (spaces, tabs and newlines), we’ll have to use a different regex:

const str = 'A B C \t D \n E';
const whitespaceRemoved = str.replace(/\s/g, '');

console.log(whitespaceRemoved); // ABC

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.