-
Notifications
You must be signed in to change notification settings - Fork 2
JS String Prototype Substr
Gets a substring beginning at the specified location and having the specified length.
str.substr(start[, length])
start
Location at which to begin extracting characters. If a negative number is given, it is treated as strLength + start where strLength is the length of the string (for example, if start is -3 it is treated as strLength - 3.)
length
Optional. The number of characters to extract.
The characters in a string beginning at the specified location through the specified number of characters.
start
is a character index. The index of the first character is 0, and the index of the last character is 1 less than the length of the string. substr()
begins extracting characters at start and collects length characters (unless it reaches the end of the string first, in which case it will return fewer).
If start
is positive and is greater than or equal to the length of the string, substr()
returns an empty string.
If start
is negative, substr()
uses it as a character index from the end of the string. If start
is negative and abs(start)
is larger than the length of the string, substr()
uses 0 as the start index. Note: the described handling of negative values of the start argument is not supported by Microsoft JScript.
If length
is 0 or negative, substr()
returns an empty string. If length is omitted, substr()
extracts characters to the end of the string.
var str = 'abcdefghij';
console.log('(1, 2): ' + str.substr(1, 2)); // '(1, 2): bc'
console.log('(-3, 2): ' + str.substr(-3, 2)); // '(-3, 2): hi'
console.log('(-3): ' + str.substr(-3)); // '(-3): hij'
console.log('(1): ' + str.substr(1)); // '(1): bcdefghij'
console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): ab'
console.log('(20, 2): ' + str.substr(20, 2)); // '(20, 2): '
var s = "The quick brown fox jumps over the lazy dog.";
var ss = s.substr(10, 5);
document.write("[" + ss + "] <br>");
ss = s.substr(10);
document.write("[" + ss + "] <br>");
ss = s.substr(10, -5);
document.write("[" + ss + "] <br>");
// Output:
// [brown]
// [brown fox jumps over the lazy dog.]
// []
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