String.prototype.substring
Returns the part of a string between two positions.
Available since: ES1
Syntax
str.substring(indexStart, indexEnd)Parameters
| Parameter | Type | Description |
|---|---|---|
| indexStart | number | The position of the first character, counting from zero. |
| indexEnd | number | Optional. The position to stop before. To the end of the string by default. |
Return value
stringA new string with the selected characters.
Examples
Characters two to five:
console.log('JavaScript'.substring(0, 4));
console.log('JavaScript'.substring(4));Output:
Java
ScriptThe difference from slice() — negative numbers are treated as zero:
console.log('JavaScript'.substring(-6));
console.log('JavaScript'.slice(-6));Output:
JavaScript
ScriptNotes
If the first argument is greater than the second, substring() swaps them. slice() behaves more predictably, so new code usually uses it.
See also
- String.prototype.slice — Returns part of a string.
- String.prototype.indexOf — Finds the position of the first occurrence of a substring.
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.