Skip to content

JavaScript Tutorial Strings

JavaScript slice() and substring()

Lesson 32 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

To take a piece of a string, use slice() or substring(). Both take a start position and an end position, and the end is not included.

script.js
JS
const word = "JavaScript";

console.log(word.slice(0, 4));  // → Java
console.log(word.slice(4));     // → Script  (to the end)
console.log(word.slice(4, 6));  // → Sc

Positions count from 0, so slice(0, 4) takes characters 0, 1, 2 and 3.

Negative numbers

slice() accepts negative numbers, which count from the end.

script.js
JS
const word = "JavaScript";

console.log(word.slice(-6));      // → Script
console.log(word.slice(0, -6));   // → Java
console.log(word.slice(-3, -1));  // → ip

substring

substring() works almost the same, but it treats negative numbers as 0 and swaps its arguments if the first is bigger.

script.js
JS
const word = "JavaScript";

console.log(word.substring(0, 4));  // → Java
console.log(word.substring(4, 0));  // → Java  (swapped)
console.log(word.substring(-3, 4)); // → Java  (-3 becomes 0)

Which one?

Use slice(). It behaves the way you expect, including negative numbers, and it matches Array.prototype.slice(). substring() is fine to read in existing code. There is also a method named substr(). It is considered legacy, so avoid it.

Practical examples

script.js
JS
const email = "maya@example.com";
const at = email.indexOf("@");

console.log(email.slice(0, at));   // → maya
console.log(email.slice(at + 1));  // → example.com

const filename = "photo.final.jpg";
console.log(filename.slice(filename.lastIndexOf(".") + 1)); // → jpg
script.js
JS
const long = "A very long headline that needs shortening";
const short = long.length > 20 ? long.slice(0, 20) + "..." : long;
console.log(short); // → A very long headline...
lightbulb
Same idea for arrays
The array method slice() takes the same arguments and also leaves the original untouched.