EN
JavaScript - String substring() method example
14
points
// ONLINE-RUNNER:browser;
// index: 012
var text = "abc";
console.log( text.substring(0) ); // abc
console.log( text.substring(1) ); // bc
console.log( text.substring(2) ); // c
console.log( text.substring(3) ); //
console.log( text.substring(0, 0) ); //
console.log( text.substring(0, 1) ); // a
console.log( text.substring(0, 2) ); // ab
console.log( text.substring(0, 3) ); // abc
1. Documentation
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. |
2. String
substring
with one argument example
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.
// ONLINE-RUNNER:browser;
// index: 012
var text = "abc";
console.log( text.substring(0) ); // abc
console.log( text.substring(1) ); // bc
console.log( text.substring(2) ); // c
console.log( text.substring(3) ); //
3. String
substring
with two arguments example
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.
// ONLINE-RUNNER:browser;
// index: 012
var text = "abc";
console.log( text.substring(0, 0) ); //
console.log( text.substring(0, 1) ); // a
console.log( text.substring(0, 2) ); // ab
console.log( text.substring(0, 3) ); // abc
console.log( text.substring(1, 1) ); //
console.log( text.substring(1, 2) ); // b
console.log( text.substring(1, 3) ); // bc
console.log( text.substring(0, 3) ); // abc
console.log( text.substring(2, 3) ); // c
console.log( text.substring(3, 3) ); //
console.log( text.substring(0, text.length ) ); // abc
console.log( text.substring(0, text.length - 1) ); // ab
console.log( text.substring(0, text.length - 2) ); // a
4. String
substring
with swapped arguments example
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.
// ONLINE-RUNNER:browser;
// index: 012
var text = "abc";
console.log( text.substring(3, 0) ); // abc
console.log( text.substring(2, 0) ); // ab
console.log( text.substring(1, 0) ); // a
5. String
substring
with negative arguments example
When arguments are negative then they are converted to 0.
// ONLINE-RUNNER:browser;
// index: 012
var text = "abc";
console.log( text.substring(-1, 3) ); // abc
console.log( text.substring(-2, 3) ); // abc
console.log( text.substring(-3, 3) ); // abc
console.log( text.substring(-1, -3) ); //