JavaScript Code

slice() vs substring() in JavaScript

slice() vs substring()

The syntax are same.

slice(start, end)
substring(start, end)

But, if start and/or end are negative values,

  • slice() treats them as positions from the end towards start in reverse
  • substring() treats them as 0


1. slice(-8, 9)

let name = 'appleisgreat';
let output = name.slice(-8, 9); //negative start

2. substring(-8, 9)

let name = 'appleisgreat';
let output = name.substring(-8, 9); //negative start

Copyright @2022