Tari Ibaba

Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

How to Get the Last N Characters of a String in JavaScript

To get the last N characters of a string in JavaScript, call the slice() method on the string, passing -N as an argument. For example, str.slice(-3) returns a new string containing the last 3 characters of str.

const str = 'Coding Beauty';

const last3 = str.slice(-3);
console.log(last3); // uty

const last6 = str.slice(-6);
console.log(last6); // Beauty

const last10 = str.slice(-10);
console.log(last10); // ing Beauty

The String() slice() method returns the portion of a string between the start and end indexes, which are specified by the first and second arguments respectively. When we only specify a start index, it returns the entire portion of the string after this start index.

When we pass a negative number as an argument, slice() counts backward from the last string character to find the equivalent index. So passing -N to slice() specifies a start index of str.length - N.

const str = 'Coding Beauty';

const last6 = str.slice(-6);
console.log(last6); // Beauty

const last6Again = str.slice(str.length - 6);
console.log(last6Again); // Beauty

Tip

If we try to get more characters than the string contains, slice() returns the entire string instead of throwing an error.

const str = 'Coding Beauty';

const last50 = str.slice(-50);
console.log(last50); // Coding Beauty

In this example, we tried to get the last 50 characters of the string by passing -50 as the first argument, but the string 'Coding Beauty' contains only 13 characters. Hence, we get the entire string from slice().

Note

We can use substring() in place of slice() to get the first N characters of a string:

const str = 'Coding Beauty';

const last3 = str.substring(str.length - 3);
console.log(last3); // uty

However, we have to manually calculate the start index ourselves with str.length - N, which makes the code less readable. This is because unlike slice(), substring() uses 0 as the start index if a negative number is passed.

const str = 'Coding Beauty';

// -3 is negative, uses 0 instead
const notLast3 = str.substring(-3);

console.log(notLast3); // Coding Beauty

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

To get the last two characters of a string in JavaScript, call the slice() method on the string, passing -2 as an argument. For example, str.slice(-2) returns a new string containing the last two characters of str.

const str = 'Coding Beauty';

const last2 = str.slice(-2);
console.log(last2); // ty

The String() slice() method returns the portion of a string between the start and end indexes, which are specified by the first and second arguments respectively. When only a start index is specified, it returns the entire portion of the string after this start index.

When we pass a negative number as an argument, slice() counts backward from the last string character to find the equivalent index. So passing -2 to slice() specifies a start index of str.length - 2.

const str = 'Coding Beauty';

const last2 = str.slice(-2);
console.log(last2); // ty

const last2Again = str.slice(str.length - 2);
console.log(last2Again); // ty

Tip

If we try to get more characters than the string contains, slice() returns the entire string instead of throwing an error.

const str = 'Coding Beauty';

const last50 = str.slice(-50);
console.log(last50); // Coding Beauty

In this example, we tried to get the last 50 characters of the string by passing -50 as the first argument, but the string 'Coding Beauty' contains only 13 characters. Hence, we get the entire string from slice().

Note

We can use substring() in place of slice() to get the first two characters of a string:

const str = 'Coding Beauty';

const last3 = str.substring(str.length - 3);
console.log(last3); // uty

However, we have to manually calculate the start index ourselves with str.length - 2, which makes the code less readable. This is because unlike slice(), substring() uses 0 as the start index if we pass a negative number.

const str = 'Coding Beauty';

// -2 is negative, uses 0 instead
const notLast2 = str.substring(-2);

console.log(notLast2); // Coding Beauty

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

1. String slice() Method

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

const str = 'Coding Beauty';

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

const first6 = str.slice(0, 6);
console.log(first6); // Coding

const first8 = str.slice(0, 8);
console.log(first8); // Coding B

The String slice() method extracts 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 N is a substring containing only the first N 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

To get the first N characters of a string, we can also call the substring() method on the string, passing 0 and N as the first and second arguments respectively. For example, str.substring(0, 3) returns a new string containing the first 3 characters of str.

const str = 'Coding Beauty';

const first3 = str.substring(0, 3);
console.log(first3); // Cod

const first5 = str.substring(0, 5);
console.log(first5); // Codin

const first11 = str.substring(0, 11);
console.log(first11); // Coding Beau

Like slice(), substring() 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 first3 = str.substring(0, 3);
console.log(first3); // Cod

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

Tip

The slice() and substring() methods work similarly for our scenario, but this isn’t always the case. 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)

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.