-
Notifications
You must be signed in to change notification settings - Fork 0
JS String Prototype Substring
The substring()
method returns a subset of a string between one index and another, or through the end of the string.
str.substring(indexStart[, indexEnd])
indexStart
An integer between 0 and the length of the string, specifying the offset into the string of the first character to include in the returned substring.
indexEnd
Optional. An integer between 0 and the length of the string, which specifies the offset into the string of the first character not to include in the returned substring.
substring()
extracts characters from indexStart
up to but not including indexEnd
. In particular:
- If
indexStart
equalsindexEnd
,substring()
returns an empty string. - If
indexEnd
is omitted,substring()
extracts characters to the end of the string. - If either argument is less than 0 or is
NaN
, it is treated as if it were 0. - If either argument is greater than
stringName.length
, it is treated as if it werestringName.length
.
If indexStart
is greater than indexEnd
, then the effect of substring()
is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1)
.
var anyString = 'Mozilla';
// Displays 'Moz'
console.log(anyString.substring(0, 3));
console.log(anyString.substring(3, 0));
// Displays 'lla'
console.log(anyString.substring(4, 7));
console.log(anyString.substring(7, 4));
// Displays 'Mozill'
console.log(anyString.substring(0, 6));
// Displays 'Mozilla'
console.log(anyString.substring(0, 7));
console.log(anyString.substring(0, 10));
var s = "The quick brown fox jumps over the lazy dog.";
var ss = s.substring(10, 15);
document.write(ss);
// Output:
// brown
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links