Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.substring()

Reference for JavaScript String.prototype.substring(): extract characters between two indexes, how it swaps arguments and treats negatives, and vs slice().

The substring() method returns the part of a string between a start index and an end index. The start is included and the end is excluded. If you leave out the end, the result runs to the end of the string.

It does the same job as slice() for ordinary positive indexes, but it handles unusual arguments differently: it swaps the two indexes when the start is larger, and it treats negative numbers as 0. Those quirks are why many style guides prefer slice().

JavaScript
"JavaScript".substring(4, 10); // "Script"

Try it

JS Basic use

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Swapping and negatives

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string.substring(indexStart)
string.substring(indexStart, indexEnd)
Name Description
indexStart Index of the first character to include. Converted to an integer; NaN and negative values become 0; values above the length become the length.
indexEnd Index of the first character to exclude. Optional; if omitted or undefined, the result continues to the end. Clamped the same way as indexStart.

Return value: a new string containing the characters between the two indexes.

Exceptions: none.

Usage notes

  • Arguments are swapped if indexStart is greater than indexEnd, so substring(4, 1) and substring(1, 4) are the same. slice(4, 1) returns an empty string instead.
  • Negative values mean 0, so substring(-3) returns the whole string. To take the last three characters, use slice(-3).
  • Equal indexes give an empty string.
  • Clamping: nothing throws for out-of-range values; they are limited to the string bounds.
  • Not the same as substr(). substr(start, length) takes a length as its second argument and is a legacy feature. Do not use it in new code.
  • Code units: indexes count UTF-16 code units, so cutting inside a surrogate pair leaves a lone surrogate. Check with isWellFormed() if text may contain emoji.
  • Immutability: the original string never changes.
  • Which to choose: slice() for predictable behavior and negative indexes; substring() is fine when its swap-and-clamp behavior is exactly what you want.

Browser support

String.prototype.substring() is supported in every browser.