Javascript - String substring() Method

The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.

Description

The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.

If "start" is greater than "end", this method will swap the two arguments, str.substring(1, 4) is the same as str.substring(4, 1).

If either "start" or "end" is less than 0, it is defaulted to 0.

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

Syntax

string.substring(start, end)

Parameter Values

Parameter Require Description
start Required. The position where to start the extraction. First character is at index 0
end Optional. The position (up to, but not including) where to end the extraction. If omitted, it extracts the rest of the string

Return

A new String containing the extracted characters

Example

Extract characters from a string:

Demo

//extract characters from the string.
var str = "Hello world!";
var res = str.substring(1, 4);
console.log(res);/*from   www .  jav  a 2s .c  o m*/

//Begin the extraction at position 2, and extract the rest of the string:
var str = "Hello world!";
var res = str.substring(2);
console.log(res);

//If "start" is greater than "end", it will swap the two arguments:
var str = "Hello world!";
var res = str.substring(4, 1);
console.log(res);

//If "start" is less than 0, it will start extraction from index position 0:
//extract characters from the string.
var str = "Hello world!";
var res = str.substring(-3);
console.log(res);

//Extract only the first character:
var str = "Hello world!";
var res = str.substring(0, 1);
console.log(res);

//Extract only the last character:
var str = "Hello world!";
var res = str.substring(11, 12);
console.log(res);

Result