Slicing Strings

Extract part of a string with slice and substring.

Syntaxstr.slice(start, end)

Extract a portion of a string using slice(start, end). The character at end is not included.

Negative indexes

slice() accepts negative numbers, counting from the end of the string. slice(-4) takes the last four characters.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Extract the file extension from a filename string to validate the upload type.
  • Truncate a long product description to 150 characters and append an ellipsis for a preview card.
  • Pull a date substring from an ISO timestamp to display only the date portion in the UI.

More examples

Slice start and end positions

Extracts the date portion of an ISO timestamp by slicing characters 0 through 9.

Example · js
const timestamp = "2024-07-15T14:30:00Z";
const date = timestamp.slice(0, 10);
console.log(date); // "2024-07-15"

Negative index to get extension

Uses lastIndexOf to find the dot position, then slice to extract the file extension.

Example · js
const filename = "report_Q3.xlsx";
const ext = filename.slice(filename.lastIndexOf("."));
console.log(ext); // ".xlsx"

Truncate with ellipsis

Wraps slice in a utility function that appends an ellipsis when the string exceeds the max length.

Example · js
function truncate(str, max) {
  return str.length > max ? str.slice(0, max) + "\u2026" : str;
}
console.log(truncate("A very long product description here", 20));

Discussion

  • Be the first to comment on this lesson.