[string].substring(start, end)
When doing string parsing or manipulation you usually need to find substrings of strings. You need to use a variable containing a string, followed by a dot ("."), followed by the function name substring with two number arguments. Recall the first letter of a string is at position 0 and the last letter is at position length-1.
Examples
Example: chop chop
var word="supercalifragilisticexpialidocious";
console.log(word.substring(0, word.length));
console.log(word.substring(1, word.length-1));
console.log(word.substring(2,3));
console.log(word.substring(3,2));
Example: first and last
See if the first letter is the same as the last letter in a word.
// See if the first letter is the same as the last letter in a word.
var word="racecar";
var first=word.substring(0,1);
var last=word.substring(word.length-1,word.length);
console.log(first == last);
Example: palindrome
Check if a word is a palindrome.
// Check if a word is a palindrome.
var word="racecar";
while(word.length>1 && word.substring(0,1)==word.substring(word.length-1,word.length)) {
word=word.substring(1,word.length-1);
}
if(word.length==0 || word.length==1) console.log("palindrome");
else console.log("not palindrome");
Syntax
[string].substring(start, end)
Parameters
Name | Type | Required? | Description |
---|---|---|---|
string | string | The string to find a substring of. | |
start | number | The starting position for the substring. | |
end | number | (end-1) is the ending position for the substring. |
Returns
Tips
- substring() assumes start <=end, or swaps them if they are not.
Found a bug in the documentation? Let us know at support@code.org.