JavaScript String substring()
Examples
Extract a substring from text:
let result = text.substring(1, 4);
Start from position 2:
More examples below.
Description
The substring()
method extracts characters, between two indices (positions), from a string,
and returns the substring.
The substring()
method extracts characters from start to end (exclusive).
The substring()
method does not change the original string.
If start is greater than end, arguments are swapped: (4, 1) = (1, 4).
Start or end values less than 0, are treated as 0.
Syntax
Parameters
Start position.
First character is at index 0.
End position (up to, but not including).
If omitted: the rest of the string.
Return Value
More Examples
If start is greater than end, parameters are swapped:
If "start" is less than 0, it will start from index 0:
Only the first:
Only the last:
Browser Support
substring()
is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |