Using string substring() or slice() in JavaScript

In JavaScript, both substring() and slice() are string methods used to extract a portion of a string. They share some similarities:

substring(indexStart)
substring(indexStart, indexEnd)

slice(indexStart)
slice(indexStart, indexEnd)
  • They take two arguments: the start and end indexes of the substring.
  • If the end index is omitted, they extract characters to the end of the string.
  • If either argument is greater than the string’s length, they use the string’s length instead.
let str = "Hello, World!";
console.log(str.substring(7, 12)); // "World"
console.log(str.slice(7, 12)); // "World"

The main difference between substring() and slice() in JavaScript is how they handle negative or out-of-range arguments. Here is a summary of their behaviors:

  • substring() will treat any negative or NaN argument as 0, and will swap the arguments if the first one is greater than the second one.
  • slice() will treat any negative argument as an offset from the end of the string, and will return an empty string if the first argument is greater than the second one.

For example:

let str = "Hello, world!";
console.log(str.substring(-1, 4)); // "Hell"
console.log(str.substring(5, 2)); // "llo"
console.log(str.slice(-5, -2)); // "orl"
console.log(str.slice(5, 2)); // ""

Use slice() when you need to work with negative indices or extract from the end of the string. Use substring() for simple extractions where you’re sure of the index order.