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 Substring Between Two Characters in JavaScript

1. String substring(), indexOf() and lastIndexOf() Methods

To get the substring of a string between two of its characters in JavaScript, call the slice() method on the string, passing the index after the first occurrence of the first character as the first argument, and the index of the last occurrence of the second character as the second argument. For example:

function getSubstring(str, char1, char2) {
  return str.substring(
    str.indexOf(char1) + 1,
    str.lastIndexOf(char2)
  );
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, ':', ';');
console.log(substr1); // two

const str2 = 'one?two!three';
const substr2 = getSubstring(str2, '?', '!');
console.log(substr2); // two

The String indexOf() method returns the position of the first occurrence of a value in a string. On the other hand, lastIndexOf() returns the position of the last occurrence of a value in a string.

The String substring() method returns the portion of a string between the start and end indexes, specified by the first and second arguments respectively. We add 1 to the result of indexOf() because we don’t want the first character to be included in the substring that we’re trying to get. However, we don’t need to subtract 1 from the result of lastIndexOf(), because substring() already excludes the character at the specified end index.

If the value doesn’t exist in the string, both indexOf() and lastIndexOf() will return -1. This means that when the first character doesn’t exist in the string, all of the string from the start to the last occurrence of the second character will be included in the string.

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, '-', ';');
console.log(substr1); // one:two

Also, when the second character doesn’t exist, all of the string from the beginning to the first occurence of the first character will be included in the string.

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, ':', '-');
console.log(substr1); // one

Depending on our use case, this might not be what we want. If we want an empty string ('') to be returned when either of the characters doesn’t exist, we’ll need to explicitly check for this:

function getSubstring(str, char1, char2) {
  const char1Index = str.indexOf(char1);
  const char2Index = str.lastIndexOf(char2);
  if (char1Index === -1) return '';
  if (char2Index === -1) return '';
  return str.substring(char1Index, char2Index);
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, '-', ';');
console.log(substr1); // '' (empty string)

const substr2 = getSubstring(str1, ':', '-');
console.log(substr2); // '' (empty string)

2. String split(), Array slice(), and Array join() Methods

Here’s another way to get the substring of a string between two of its characters:

function getSubstring(str, char1, char2) {
  return str
    .split(char1)
    .slice(1)
    .join('')
    .split(char2)
    .slice(0, -1)
    .join('');
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, ':', ';');
console.log(substr1); // two

const str2 = 'one?two!three';
const substr2 = getSubstring(str2, '?', '!');
console.log(substr2); // two

The String split() method divides a string using a specified separator.

const str1 = 'one:two;three';

// [ 'one', 'two;three' ]
console.log(str1.split(':')); 

The Array slice() methods extracts the elements of an array between the start and end indexes, which are specified by the first and second arguments respectively. We pass 1 as the first argument without specifying a second, so slice() extracts from the element at index 1 to the end of the string.

// ['two;three'];
console.log([ 'one', 'two;three' ].slice(1));

We call the Array join() method on the result of slice() to concatenate the elements of the array into a string.

const str1 = 'one:two;three';

// two;three
console.log(['two;three'].join(''));

We split this result again, this time by the second character.

// ['two', 'three'];
console.log('two;three'.split(';'));

We call slice() on the array resulting from this split, passing 0 and -1 as arguments, to copy all the array elements except the last one to a new array.

// [ 'two' ]
console.log(['two', 'three'].slice(0, -1));

Finally, we call join() on this result to get the string between the two characters.

Unlike the first method, this approach handles the case where one of the characters is not in the string by returning an empty string.

function getSubstring(str, char1, char2) {
  return str
    .split(char1)
    .slice(1)
    .join('')
    .split(char2)
    .slice(0, -1)
    .join('');
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, '-', ';');
console.log(substr1); // '' (empty string)

const substr2 = getSubstring(str1, ':', '-');
console.log(substr2); // '' (empty string)

How to Add Minutes to a Date in JavaScript

1. Date setMinutes() and getMinutes() Methods

To add minutes to a Date in JavaScript, call the getMinutes() method on the Date to get the minutes, then call the setMinutes() method on the Date, passing the sum of getMinutes() and the minutes to add.

function addMinutes(date, minutes) {
  date.setMinutes(date.getMinutes() + minutes);

  return date;
}

const date = new Date('2022-05-15T00:00:00.000Z');

const newDate = addMinutes(date, 10);

// 2022-05-15T00:10:00.000Z
console.log(newDate);

Our addMinutes() function takes a Date and the number of minutes to add as arguments, and returns the same Date with the newly added minutes.

The Date getMinutes() method returns a number between 0 and 59 that represents the minutes of the Date.

The Date setMinutes() method takes a number representing minutes and set the minutes of the Date to that number.

If the minutes you specify would change the hour, day, month, or year of the Date, setMinutes() automatically updates the Date information to reflect this.

// 12:00 AM on May 15, 2022
const date = new Date('2022-05-15T00:00:00.000Z');

date.setMinutes(date.getMinutes() + 150);

// 2:30 AM on May 15, 2022
console.log(date); // 2022-05-15T02:30:00.000Z

In this example, passing 150 to setMinutes() increments the Date hours by 2 (120 minutes) and sets the minutes to 30.

Avoiding Side Effects

The setMinutes() method mutates the Date object it is called on. This introduces a side effect into our addMinutes() function. To avoid modifying the passed Date and create a pure function, make a copy of the Date and call setMinutes() on this copy, instead of the original:

function addMinutes(date, minutes) {
  const dateCopy = new Date(date);
  dateCopy.setMinutes(date.getMinutes() + minutes);

  return dateCopy;
}

const date = new Date('2022-05-15T00:00:00.000Z');

const newDate = addMinutes(date, 10);

console.log(newDate); // 2022-05-15T00:10:00.000Z

// Original not modified
console.log(date); // 2022-05-15T00:00:00.000Z

Tip

Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about. This makes it a good practice to limit the number of side-effects in your programs.

2. date-fns addMinutes()

Alternatively, you can use the pure addMinutes() function from the date-fns NPM package to quickly add minutes to a Date.

import { addMinutes } from 'date-fns';

const date = new Date('2022-05-15T00:00:00.000Z');
const newDate = addMinutes(date, 10);

console.log(newDate); // 2022-05-15T00:10:00.000Z

// Original not modified.
console.log(date); // 2022-05-15T00:00:00.000Z

How to Split a Number into an Array in JavaScript

1. Array.from() Method

To split a number into an array in JavaScript, call the Array.from() method, passing the number converted to a string as the first argument, and the Number constructor as the second, i.e., Array.from(String(num), Number). For example:

function splitIntoArray(num) {
  return Array.from(String(num), Number);
}

const arr1 = splitIntoArray(1234);
console.log(arr1); // [ 1, 2, 3, 4 ]

const arr2 = splitIntoArray(4901);
console.log(arr2); // [ 4, 9, 0, 1 ]

The static Array from() method creates a new array from an array-like object, like a String or a Set.

// [ '1', '2', '3', '4' ]
console.log(Array.from('1234'));

The second argument we pass to from() is a map function that is called on every element of the array. We pass the Number constructor function so that each item in the array will be converted to a number.

We can do this more explicitly with the Array map() instance method:

const num = 1234;

// ['1', '2', '3', '4'];
const arrOfStrs = Array.from(String(num));

const arrOfNums = arrOfStrs.map((str) => Number(str));

console.log(arrOfNums); // [ 1, 2, 3, 4 ]

2. String split() Method

We can also split a number into an array with the String split() method. To do this:

  1. Convert the number to a string.
  2. Call the split() method on the string to convert it into an array of stringified digits.
  3. Call the map() method on this array to convert each string to a number.
function splitIntoArray(num) {
  return String(num).split('').map(Number);
}

const arr1 = splitIntoArray(1234);
console.log(arr1); // [ 1, 2, 3, 4 ]

const arr2 = splitIntoArray(4901);
console.log(arr2); // [ 4, 9, 0, 1 ]

The String split() method divides a string into an array of substrings based on the specified separator. We specify an empty string ('') as the separator to split the string into an array of all its characters.

// ['1', '2', '3', '4'];
console.log('1234'.split(''));

We call map() on this string array, passing the Number constructor to convert each element to a number and create a new number array.

// [ 1, 2, 3, 4 ]
console.log(['1', '2', '3', '4'].map(Number));

Tip

This:

// [1, 2, 3, 4]
console.log(['1', '2', '3', '4'].map(Number));

produces the same results as this:

// [ 1, 2, 3, 4 ]
console.log(['1', '2', '3', '4']
  .map((str) => Number(str)));

Although you might prefer to be more explicit with the second way, so you can see exactly what callback arguments you’re passing to Number.

How to Find the Even Numbers in an Array with JavaScript

1. Array filter() Method

To find the even numbers in array with JavaScript, call the filter() method on the array, passing a callback that returns true when the element is even, and false otherwise

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = numbers.filter((num) => num % 2 === 0);

// [10, 8, 18, 6]
console.log(evens);

The filter() method creates a new array with all the elements that pass the test specified in the testing callback function. Only even numbers have a remainder of 0 when divided by 2, so filter() returns an array of all the even numbers in the original array.

Note: filter() preserves the order of the elements from the original array.

2. Array forEach() Method

Alternatively, we can find the odd numbers in an array 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 even.

const numbers = [7, 10, 15, 8, 13, 18, 6];

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

// [ 10, 8, 18, 6 ]
console.log(evens);

3. for…of Loop

We can use the for...of loop in place of forEach() to iterate through the array and find the even numbers.

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = [];
for (const num of numbers) {
  if (num % 2 === 0) {
    evens.push(num);
  }
}

// [ 10, 8, 18, 6 ]
console.log(evens);

4. Traditional for Loop

And we can’t forget the traditional for loop:

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = [];
for (let i = 0; i < numbers.length; i++) {
  const num = numbers[i];
  if (num % 2 === 0) {
    evens.push(num);
  }
}

// [ 10, 8, 18, 6 ]
console.log(evens);

Performance Comparison

Let’s compare the performance of these four methods using an array with 10 million elements (with elements from 1 to 10 million).

const numbers = [...Array(10000000)].map(
  (_, index) => index + 1
);

function measurePerf(label, method) {
  console.time(label);
  method();
  console.timeEnd(label);
}

measurePerf('filter', () => {
  const evens = numbers.filter((num) => num % 2 === 0);
});

measurePerf('forEach', () => {
  const evens = [];
  numbers.forEach((num) => {
    if (num % 2 === 0) {
      evens.push(num);
    }
  });
});

measurePerf('for...of', () => {
  const evens = [];
  for (const num of numbers) {
    if (num % 2 === 0) {
      evens.push(num);
    }
  }
});

measurePerf('for', () => {
  const evens = [];
  for (let i = 0; i < numbers.length; i++) {
    const num = numbers[i];
    if (num % 2 === 0) {
      evens.push(num);
    }
  }
});

Results

Average

  • filter(): 300.216 ms
  • forEach(): 286.516 ms
  • for...of: 298.750 ms
  • for: 137.778 ms

The traditional for loop consistently comes out on top in this comparison. This doesn’t mean you must use it all the time, however. It’s not very often that you need to filter through an array with 10 million elements – in typical use cases, the performance gains you’d get from the for loop will be minuscule. In most scenarios, you’d be better off using filter() due to its greater conciseness and readability, and if you prefer the functional approach, despite its slower speed.

How to Resolve a Promise from Outside in JavaScript

To resolve a promise from outside in JavaScript, assign the resolve callback to a variable defined outside the Promise constructor scope, then call the variable to resolve the Promise. For example:

let promiseResolve;
let promiseReject;

const promise = new Promise((resolve, reject) => {
  promiseResolve = resolve;
  promiseReject = reject;
});

promiseResolve();

Now why would we need to do something like this? Well, maybe we have an operation A currently in progress, and the user wants another operation B to happen, but B must wait for A to complete. Let’s say we have a simple social app where users can create, save and publish posts.

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Resolving a Promise from Outside</title>
  </head>
  <body>
    <p>
      Save status:
      <b><span id="save-status">Not saved</span></b>
    </p>
    <p>
      Publish status:
      <b><span id="publish-status">Not published</span></b>
    </p>
    <button id="save">Save</button>
    <button id="publish">Publish</button>
    <script src="index.js"></script>
  </body>
</html>
A simple app where users can create, save and publish posts.
Publish doesn’t happen until after save.

What if a post is currently being saved (operation A) and the user wants to publish the post (operation B) while saving is ongoing?. If we don’t want to disable the “Publish” button when the save is happening, we’ll need to ensure the post is saved before publish happens.

index.js


// Enable UI interactivity
const saveStatus = document.getElementById('save-status');
const saveButton = document.getElementById('save');
const publishStatus = document.getElementById(
  'publish-status'
);
const publishButton = document.getElementById('publish');
saveButton.onclick = () => {
  save();
};
publishButton.onclick = async () => {
  await publish();
};

let saveResolve;
let hasSaved = false;

function save() {
  hasSaved = false;
  saveStatus.textContent = 'Saving...';
  setTimeout(() => {
    saveResolve();
    hasSaved = true;
    saveStatus.textContent = 'Saved';
  }, 3000);
}

async function waitForSave() {
  if (!hasSaved) {
    await new Promise((resolve) => {
      saveResolve = resolve;
    });
  }
}

async function publish() {
  publishStatus.textContent = 'Waiting for save...';
  await waitForSave();
  publishStatus.textContent = 'Published';
  return;
}

The key parts of this code are the save() and waitForSave() functions. When the user clicks “Publish”, waitForSave() is called. If the post has already been saved, the Promise returned from waitForSave() resolves immediately, otherwise it assigns its resolve callback to an external variable that will be called after the save. This makes publish() wait for the timeout in save() to expire before continuing.

Post is saved before publish happens.

We can create a Deferred class to abstract and reuse this logic:

class Deferred {
  constructor() {
    this.promise = new Promise((resolve, reject) => {
      this.reject = reject;
      this.resolve = resolve;
    });
  }
}

const deferred = new Deferred();

// Resolve from outside
deferred.resolve();

Now the variables to resolve/reject a Promise and the Promise itself will be contained in the same Deferred object.

We can refactor our code to use this class:

// Enable UI interactivity
// ...

const deferredSave = new Deferred();
let hasSaved = false;

function save() {
  hasSaved = false;
  saveStatus.textContent = 'Saving...';
  setTimeout(() => {
    deferredSave.resolve();
    hasSaved = true;
    saveStatus.textContent = 'Saved';
  }, 3000);
}

async function waitForSave() {
  if (!hasSaved) await deferredSave.promise;
}

async function publish() {
  // ...
}

And the functionality will work as before:

The functionality works as before after the refactor.

How to Extract a Number from a String in JavaScript

1. String replace() Method

To extract a number from a string in JavaScript, call the replace() method on the string with a regex to replace all the non-digit characters in the original string. For example:

const str = 'The number 345 has three digits';

const replaced = str.replace(/\D/g, '');
console.log(replaced); // 345

The String replace() method returns a new string with the matches of a pattern replaced by a replacement. We pass a regular expression that matches all the non-digit characters so that we can replace them with an empty string ('') to remove them.

The \D regex metacharacter matches any non-digit characters in a string.

The g (global) flag specifies that every occurrence of a non-digit character in the string should be matched by the regex.

If we don’t pass the global flag, only the first non-digit character in the input string will be matched and replaced:

const str = 'The number 345 has three digits';

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

console.log(replaced); // he number 345 has three digits

2. String match() Method

To extract a number from a string, we can also call the match() method on the string, passing a regex that matches a consecutive sequence of digits. For example:

const str = 'The number 345 has three digits';

const matches = str.match(/\d+/);
const numStr = matches[0];

console.log(numStr); // 345

The String match() method matches a string against a regular expression and returns the results. In our case, the matched number is the first item of the array, so we access the 0 property with bracket notation to get it.

The \d metacharacter is used to find a digit in a string. We add the + to \d in order to find a consecutive sequence of digits.

This second method is better when trying to extract each number in the string separately, as it treats a consecutive sequence of digits as a separate match. To extract each number separately, we’ll need to add the g flag:

const str = 'The numbers 345 and 847 have three digits';

const matches = str.match(/\d+/g);
console.log(matches); // [ '345', '847' ]

Note

When no digits can be found, the match() method will return null:

const str = 'There are no numbers in this string';

const matches = str.match(/\d+/g);
console.log(matches); // null

How to Add Hours to a Date in JavaScript

In this article, we’re going to learn how to easily add number of hours to a Date object in JavaScript.

1. Date setHours() and getHours() methods

To add hours to a Date in JavaScript:

  1. Call the getHours() on the Date to get the hours.
  2. Add the hours.
  3. Pass the sum to the setHours() method.

For example:

function addHours(date, hours) {
  date.setHours(date.getHours() + hours);

  return date;
}

const date = new Date('2022-05-15T12:00:00.000Z');

const newDate = addHours(date, 5);

console.log(newDate); // 2022-05-15T17:00:00.000Z

The Date getHours() method returns a number between 0 and 23 that represents the hours of a particular date.

The Date setHours() method sets the hours of a date to a specified number.

If the hours added would increase the day, month, or year of the DatesetHours() will automatically update the date information to reflect this.

// 11 PM on June 17, 2022
const date = new Date('2022-06-17T23:00:00.000Z');

date.setHours(date.getHours() + 4);

// 3 AM on June 18, 2022 (next day)
console.log(date); // 2022-06-18T03:00:00.000Z

In this example, increasing the hours of the date by 4 moves the day forward to June 18, 2022.

Avoid side effects

The setHours() method mutates the Date object it is called on. This introduces a side effect into our addHours() function. To make a pure function, create a copy of the Date and call setHours() on this copy, instead of the original. For example:

function addHours(date, hours) {
  // πŸ‘‡ Make copy with "Date" constructor.
  const dateCopy = new Date(date);

  dateCopy.setHours(dateCopy.getHours() + hours);

  return dateCopy;
}

const date = new Date('2022-05-15T12:00:00.000Z');

const newDate = addHours(date, 2);
console.log(newDate); // 2022-05-15T14:00:00.000Z

// πŸ‘‡ Original not modified
console.log(date); // 2022-05-15T12:00:00.000Z

Tip: Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about, as they always give the same output for a particular input. This makes it a good practice to limit the number of side effects in your code.

2. date-fns addHours() function

Alternatively, you can use the addHours() function from the date-fns NPM package to quickly add hours to a Date. It works like our pure addHours() function.

import { addHours } from 'date-fns';

const date = new Date('2022-05-15T12:00:00.000Z');

const newDate = addHours(date, 4);
console.log(newDate); // 2022-05-15T16:00:00.000Z

// Original not modified
console.log(date); // 2022-05-15T12:00:00.000Z

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)