JavaScript String slice()

slice() extracts part of a string and returns a new string. The start index is included and the end index is excluded. Negative indexes count backward from the end.

const text = "Welcome to www.plus2net.com";
console.log(text.slice(0, 7)); // Welcome

slice() Syntax Top ↑

string.slice(start)
string.slice(start, end)

Use Only a Start Index Top ↑

const text = "Welcome to www.plus2net.com";
console.log(text.slice(11)); // www.plus2net.com

When end is omitted, extraction continues to the end of the string.

Use Start and End Indexes Top ↑

const text = "JavaScript";
console.log(text.slice(0, 4)); // Java

The character at the end index is not included.

Negative Indexes Count from the End Top ↑

const text = "Welcome to www.plus2net.com";
console.log(text.slice(-1));      // m
console.log(text.slice(-4));      // .com
console.log(text.slice(-12, -4)); // plus2net

More slice() Examples from the Original Tutorial Top ↑

const text = "Welcome to www.plus2net.com";
console.log(text.slice(0, 7));   // Welcome
console.log(text.slice(11, 14)); // www
console.log(text.slice(0, -7));  // removes final 7 code units

slice() vs substring() Top ↑

Both use start and end indexes, but their negative-index behavior differs. slice() counts negative indexes from the end. substring() treats negative arguments as 0 and swaps the two arguments when the start is greater than the end.

slice() vs Legacy substr() Top ↑

substr() takes start, length, not start, end, and is a legacy feature. Prefer slice() or substring() in new code.

Extract Text After a Marker Top ↑

const email = "userid@example.com";
const at = email.indexOf("@");
const domain = email.slice(at + 1);
console.log(domain); // example.com

See the email string example and indexOf() tutorial for related techniques.

Common slice() Mistakes Top ↑

  • Expecting the end index to be included.
  • Confusing the second argument with a character count.
  • Mixing up slice(), substring() and legacy substr().
  • Forgetting negative indexes count from the end.
  • Expecting slice() to modify the original string.

String Reference Lowercase Strings




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer