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

Examples

1. slice(-8, 9)

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

2. substring(-8, 9)

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

Copyright @2022