JavaScript String Slice: Syntax, Examples, and Common Uses

How-to basics · Updated November 22, 2026

Use string.slice(start, end) to get part of a JavaScript string: the character at start is included, while the character at end is not. You can omit end to take the rest of the string, or use negative indexes to count back from its end.

What the String slice() Method Does

slice() is a built-in method on JavaScript strings. It returns a string containing a selected range of the original string. It does not change the original value, which matters because JavaScript strings are immutable: methods cannot edit a string in place.

The method is useful when you know the positions of the text you want. For example, it can extract a prefix, remove a known suffix by taking everything before it, or select a section between two indexes. If you need to find text by its contents rather than by a position you already know, methods such as indexOf() can help you locate an index first.

Here is a basic example:

const language = 'JavaScript';
const part = language.slice(0, 4);
console.log(part); // Java

The result is Java because the range starts at index 0 and stops just before index 4. The original language variable still contains JavaScript.

Syntax and the Start and End Arguments

The usual syntax is text.slice(start, end). The first argument, start, identifies where the returned section begins. It is included in the result. The optional second argument, end, identifies where the section stops, and that position is excluded. This is often described as a half-open range: it includes the start boundary but not the end boundary.

If you leave out end, the result continues to the end of the string. Calling slice() without arguments returns the full string value. Although that can be valid, it is usually clearer to omit the call if no portion needs to be selected.

  • 'JavaScript'.slice(0, 4) returns 'Java'.
  • 'JavaScript'.slice(4) returns 'Script'.
  • 'JavaScript'.slice(4, 4) returns an empty string because the range has no width.

Indexes outside the string are adjusted to the available range. A start beyond the end produces an empty string. An end beyond the end behaves as though it were the string’s length. If the adjusted end is not after the adjusted start, there is no range to return, so the result is empty.

How String Indexes Work

For ordinary English text, indexes usually match the positions you expect, because each basic Latin letter occupies one JavaScript string index. Indexing starts at zero, not one. In 'cat', for example, c is at index 0, a is at index 1, and t is at index 2. Therefore, 'cat'.slice(1, 3) returns 'at'.

The exclusive end position makes it straightforward to calculate a slice length: subtract the start index from the end index. A range from 2 to 5 contains three indexed units: positions 2, 3, and 4. This convention also makes adjacent ranges fit together neatly. For example, text.slice(0, 3) followed by text.slice(3) divides a simple string at index 3 without overlapping or skipping an index.

JavaScript converts the supplied index values to integer positions. Fractional numbers are truncated toward zero; for instance, an index of 2.8 is treated like 2. Values that convert to NaN act like zero, and positions are limited to the string’s bounds. In everyday code, passing clear integer indexes is easier to read and avoids relying on these conversions.

Using Negative Indexes

A negative argument counts backward from the end of the string. In effect, JavaScript adds the string’s length to that index, then applies the usual boundary rules. This can be handy when the relevant text is near the end and you do not want to calculate its absolute position.

const file = 'report.csv';
console.log(file.slice(-3)); // csv
console.log(file.slice(0, -4)); // report

In the first call, -3 means the position three indexes from the end, so the final three units are returned. In the second, -4 marks the position four units from the end; because the end is excluded, the result leaves off the period and the three letters in the extension. This is a convenient example, but real file-name handling may need additional checks for names with no extension or with multiple dots.

Negative start and end values can be combined. For 'JavaScript'.slice(-6, -1), the range begins six positions from the end and ends one position before the end, returning 'Scrip'. As with positive indexes, if the adjusted end does not come after the adjusted start, the result is empty.

Practical Examples

Once the boundary rule is clear, many common tasks become predictable. For example, a fixed-width identifier can be separated into a prefix and remainder, provided its format is known:

const code = 'AB-4729';
const prefix = code.slice(0, 2);
const remainder = code.slice(3);
console.log(prefix); // AB
console.log(remainder); // 4729

The hyphen is at index 2, so starting the remainder at index 3 skips it. That code assumes the input always has the expected format. If the separator can move or be missing, find and validate it instead of relying on fixed positions.

A string slice can also be combined with a search. For instance, to get text before the first colon, find the colon’s index and pass that position as the exclusive end. Check for a missing colon first: indexOf() returns -1 when it cannot find the text, and using that value as a slice boundary may produce a result other than the intended fallback.

Another common use is trimming a known number of characters from one side. message.slice(1) skips the first indexed unit, while message.slice(0, -1) leaves off the final indexed unit. These operations do not check whether the skipped character is a particular symbol. If the goal is to remove a prefix only when it matches, test the prefix before slicing.

Unicode, Emoji, and What Counts as a Character

A key detail is that JavaScript string indexes count UTF-16 code units, not necessarily the characters a person sees. Basic Latin letters generally use one code unit, but many other symbols use two. The length property and slice() use the same indexing system, so indexes based on length are internally consistent even when they do not match the number of visible symbols.

For example, the string 'A😀B' has a length of 4 in JavaScript: A uses one code unit, the emoji uses two, and B uses one. A slice that selects only one of the emoji’s two code units can split the surrogate pair. The result may display as an unexpected replacement symbol or otherwise behave oddly when processed.

If an operation should treat Unicode code points as units, Array.from(text) can create an array of code-point strings, which can then be sliced as an array. But code points are not always the same as user-perceived characters: an accented letter may be represented by a base letter plus a combining mark, and some emoji are made from multiple code points. For user-visible text selection, grapheme-aware handling, such as Intl.Segmenter with grapheme granularity in supported JavaScript environments, is more appropriate. The right approach depends on whether the task concerns storage indexes, Unicode code points, or displayed characters.

String slice() Compared with substring() and substr()

slice() and substring() both return a selected section, and both use an exclusive end position. Their behavior differs in edge cases, so substituting one for the other can introduce bugs.

  • slice() supports negative indexes, counting from the end.
  • substring() treats negative arguments as zero.
  • If the first argument is greater than the second, slice() returns an empty string; substring() swaps the two positions.

For example, 'hello'.slice(4, 1) returns an empty string, while 'hello'.substring(4, 1) returns 'ell' because substring() reverses the boundaries. Choose slice() when its negative-index behavior and strict boundary order fit the task. Use substring() only when its particular behavior is wanted or when working with code that already relies on it.

You may also encounter substr(), which takes a start position and a length rather than a start and end position. It is a legacy method and is deprecated in modern JavaScript documentation; avoid choosing it for new code. Prefer slice(), which has a clearer, more widely applicable range convention.

Common Mistakes and Safer Patterns

The most frequent mistake is treating the end as inclusive. To include the character at index 5, the end argument must be at least 6. Another is forgetting that indexes begin at zero, which shifts a desired section by one position. When a result is wrong, write the string’s indexes beside its characters and check which boundaries are included.

  • Do not expect slice() to change the original string. Store or return its result if you need to use it.
  • Do not assume negative positions mean “remove this many characters” in every situation; they identify a boundary counted from the end.
  • Do not slice user-visible text by presumed character count without considering UTF-16 and grapheme boundaries.
  • Validate assumptions about separators, prefixes, or fixed-width fields before using hard-coded indexes.

For code that handles arbitrary input, combine slicing with checks. Confirm the string is present and that a searched delimiter was found before using its index. For user-entered text, consider whether the requirement is based on code units, code points, or visible grapheme clusters. These small decisions make the difference between a reliable extraction and a bug that appears only for certain languages or emoji.

Frequently Asked Questions

Does slice() change the original string?
No. JavaScript strings are immutable, and slice() returns the selected string value. Assign that result to a variable if you want to keep it; the original string remains unchanged.

Is the end index included in JavaScript slice()?
No. The start index is included and the end index is excluded. To include a character at index 5, use an end boundary of 6, assuming the string has that position.

What does slice(-1) return?
It returns the final UTF-16 code unit of the string. For ordinary single-unit characters, that is the last visible character. A supplementary Unicode symbol may use two code units, so a one-unit slice can split it.

What happens if the start index is bigger than the end index?
slice() returns an empty string when the effective end position is not after the effective start. This differs from substring(), which swaps the positions in that case.

Can I use slice() to remove the first character?
Yes. text.slice(1) returns everything after the first indexed unit. If the string can start with a multi-unit symbol and you mean its first visible character, use Unicode-aware segmentation rather than assuming one index equals one displayed character.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.