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
string.slice(start)
string.slice(start, end)
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.
const text = "JavaScript";
console.log(text.slice(0, 4)); // Java
The character at the end index is not included.
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
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
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.
substr() takes start, length, not start, end, and is a legacy feature. Prefer slice() or substring() in new code.
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.
slice(), substring() and legacy substr().slice() to modify the original string.String Reference Lowercase Strings
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.