str.substring

Category:Variables

[string].substring(start, end)

Category: Variables

Returns a string extracted from the start position to one before the end position of the original string.

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


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 Yes The string to find a substring of.
start number Yes The starting position for the substring.
end number Yes (end-1) is the ending position for the substring.

Returns

A substring from start to end-1

Tips

  • substring() assumes start <=end, or swaps them if they are not.

Found a bug in the documentation? Let us know at documentation@code.org

Found a bug in the documentation? Let us know at documentation@code.org