EN
JavaScript - String substring() method example
14 points
xxxxxxxxxx
1
// index: 012
2
var text = "abc";
3
4
console.log( text.substring(0) ); // abc
5
console.log( text.substring(1) ); // bc
6
console.log( text.substring(2) ); // c
7
console.log( text.substring(3) ); //
8
9
console.log( text.substring(0, 0) ); //
10
console.log( text.substring(0, 1) ); // a
11
console.log( text.substring(0, 2) ); // ab
12
console.log( text.substring(0, 3) ); // abc
Syntax | String.prototype.substring(indexStart[, indexEnd]) |
Parameters |
|
Result | A new string containing the specified part of the given string. |
Description | String substring returns the part of the string between the indexStart and indexEnd , or from indexStart to the end of the string. |
The example presented in this section shows how to get substring starting from the index passed as the first argument to the end of the string.
xxxxxxxxxx
1
// index: 012
2
var text = "abc";
3
4
console.log( text.substring(0) ); // abc
5
console.log( text.substring(1) ); // bc
6
console.log( text.substring(2) ); // c
7
console.log( text.substring(3) ); //
The example presented in this section shows how to get substring starting from the index passed as the first argument to the ending index passed as the second argument.
xxxxxxxxxx
1
// index: 012
2
var text = "abc";
3
4
console.log( text.substring(0, 0) ); //
5
console.log( text.substring(0, 1) ); // a
6
console.log( text.substring(0, 2) ); // ab
7
console.log( text.substring(0, 3) ); // abc
8
9
console.log( text.substring(1, 1) ); //
10
console.log( text.substring(1, 2) ); // b
11
console.log( text.substring(1, 3) ); // bc
12
13
console.log( text.substring(0, 3) ); // abc
14
console.log( text.substring(2, 3) ); // c
15
console.log( text.substring(3, 3) ); //
16
17
console.log( text.substring(0, text.length ) ); // abc
18
console.log( text.substring(0, text.length - 1) ); // ab
19
console.log( text.substring(0, text.length - 2) ); // a
In this case, the substring behaves similarly to the second example. One difference is if the first argument is bigger than the second one then they are swapped.
xxxxxxxxxx
1
// index: 012
2
var text = "abc";
3
4
console.log( text.substring(3, 0) ); // abc
5
console.log( text.substring(2, 0) ); // ab
6
console.log( text.substring(1, 0) ); // a
When arguments are negative then they are converted to 0.
xxxxxxxxxx
1
// index: 012
2
var text = "abc";
3
4
console.log( text.substring(-1, 3) ); // abc
5
console.log( text.substring(-2, 3) ); // abc
6
console.log( text.substring(-3, 3) ); // abc
7
8
console.log( text.substring(-1, -3) ); //