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".substring(4, 10); // "Script"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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
indexStartis greater thanindexEnd, sosubstring(4, 1)andsubstring(1, 4)are the same.slice(4, 1)returns an empty string instead. - Negative values mean
0, sosubstring(-3)returns the whole string. To take the last three characters, useslice(-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.