JavaScript String substring() Method

Definition and Usage

substring() The method extracts characters between two indices (positions) in the string and returns the substring.

substring() The method extracts characters from start to end (excluding).

substring() The method does not change the original string.

If start greater than endThen, swap the parameters: (4, 1) = (1, 4).

The beginning or ending value less than 0 is considered as 0.

See also:

split() method

slice() method

substr() method

Instance

Example 1

Extracting substrings from the text:

let text = "Hello world!";
let result = text.substring(1, 4);

Try it yourself

Example 2

Starting from position 2:

let result = text.substring(2);

Try it yourself

Example 3

If start greater than end, then swap the parameters:

let result = text.substring(4, 1);

Try it yourself

Example 4

If "start" is less than 0, it will start from index 0:

let result = text.substring(-3);

Try it yourself

Example 5

Only the first one:

let result = text.substring(0, 1);

Try it yourself

Example 6

Only the last one:

let result = text.substring(text.length - 1);

Try it yourself

Syntax

string.substring(start, end)

Parameter

Parameter Description
start

Required. A non-negative integer. The starting position.

The first character is at index 0.

end

Optional. A non-negative integer. The end position (at most, but not including).

If omitted, it extracts the rest of the string.

Return value

Type Description
String The string containing the extracted characters.

Technical details

Return value

Returns a new string whose value contains string a substring whose content is from start to endAll characters at position -1, with a length of end minus start.

Description

substring() The substring returned by the method includes start character, but does not include end character.

if the parameter start with end equal, then the method returns an empty string (i.e., a string with a length of 0). If start than end large, then the method will swap these two parameters before extracting the substring.

Remember that the substring includes start character, but does not include end character, the length of the returned substring is always equal to end-start.

Please note that,split() and substr() They can all extract substrings from a string. Different from these methods is that,substring() The method does not accept negative parameters.

Browser support

substring() It is an ECMAScript1 (ES1) feature.

All browsers fully support ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support

Related pages

JavaScript String

JavaScript String Methods

JavaScript String Search