How to use a slice or substr function and what is the difference between them?

Modified on Thu, 18 Jul at 9:36 AM

slice()


The `slice()` method takes two optional arguments:

  • `startIndex`: The index where you want to begin your extraction (inclusive).
  • `endIndex`: The index where you want to end your extraction (exclusive).


Syntax: 

str.slice(startIndex, endIndex)
  • If `endIndex` is omitted, `slice()` extracts to the end of the string
  • It also supports negative indices


Example:

let str = "Hello, World!";

console.log(str.slice(0, 5)); // "Hello"

console.log(str.slice(7)); // "World!"

console.log(str.slice(-6)); // "World!"


substr()


The `substr()` method also takes two arguments:

  • `startIndex`: The index where you want to begin your extraction.
  • `length`: The number of characters you want to extract (optional).

Syntax:

str.substr(startIndex, length)
  • If `length` omitted, `substr()` extracts to the end of the string
  • It also supports negative `startIndex`


Example:

let str = "Hello, World!";

console.log(str.substr(0, 5)); // "Hello"

console.log(str.substr(7)); // "World!"

console.log(str.substr(-6)); // "World!"


Key Differences


1. `slice()` uses start and end indices, while `substr()` uses start index and length.

2. `slice()` is more flexible and works consistently with arrays.

3. `substr()` is considered somewhat deprecated.


Conclusion


While `substr()` can be useful in certain scenarios, `slice()` is generally recommended due to its flexibility, consistency, and future-proofing.

However, if you want to extract all the characters from a given index to the end of the string, you can use `slice()` without the end argument:


let str = "Hello, World!";

str.slice(7); // Preferred

str.substr(7, str.length - 7); // Less ideal


Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article