JavaScript String substring()
Examples
Extract a substring from text:
let text = "Hello world!";
let result = text.substring(1, 4);
Try it Yourself »
Start from position 2:
let result = text.substring(2);
Try it Yourself »
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
string.substring(start, end)
Parameters
Parameter | Description |
start | Required. Start position. First character is at index 0. |
end | Optional. End position (up to, but not including). If omitted: the rest of the string. |
Return Value
Type | Description |
A string | A string containing the extracted characters. |
More Examples
If start is greater than end, parameters are swapped:
let result = text.substring(4, 1);
Try it Yourself »
If "start" is less than 0, it will start from index 0:
let result = text.substring(-3);
Try it Yourself »
Only the first:
let result = text.substring(0, 1);
Try it Yourself »
Only the last:
let result = text.substring(text.length - 1);
Try it Yourself »
Browser Support
substring()
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.