String Methods

Substring Method

🙋 Need help? Ask an expert now!

The substring methods returns a certain section of the original string based on the parameters in the function. There are two methods for substring, substr() and substring(). The syntax and the function of each method is shown below.

string.substr(start, length)

  • returns a substring, starting from index start for length characters
  • length is optional

string.substring(start, end)

  • returns a substring, starting from start and ending at end
  • end is optional if end is equal to the length of the string

The code sample above shows the use of both substr() and substring(). The substr() method creates a new string that consists of 5 characters starting from index 0 of the original string. Therefore, only "Hello" is printed on the first line. The substring() method creates a new string starting from the 6th index all the way to the last index of the string, 12. This prints "World!" on the console. As mentioned previously, the end parameter of the substring() method is not necessary if end is equal to the length of the string. Try removing the "12" from the method and see if the output is the same.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var animalOne = "Dog";
            var animalTwo = "Cat";
            var animalThree = "Mouse";
            animalTwo = animalOne;
            animalOne = "Frog";
            var str = animalOne.substring(2, 4) + animalTwo.substring(1, 2) + animalThree.substring(animalOne.indexOf('o'), 5);
            console.log(str);
            

What will the following code segment print to the console?