Javascript: substring() method

This article discusses the syntax and functioning of the substring() method in javascript including various examples for illustration purposes.

Usage of substring():-

Javascript’s substring() method returns a string portion between the start and end indexes or to the end of the string if the endIndex is not present.¬†

Syntax of substring():-

substring(startIndex, endIndex)

Here,

  • The index of substring() starts from zero.
  • The startIndex specifies from where the extraction will begin. The extracted string includes the character at startIndex.
  • If the startIndex value is negative, it is treated as 0.
  • The endIndex specifies to end the extraction before the endIndex. The extracted string excludes the character at endIndex.
  • The endIndex is optional.
  • If the endIndex value is negative, it is treated as 0.
  • If startIndex > endIndex, the substring() method will swap both the arguments.

Example-1 of substring():-

let dummyString = 'Javascript*'
dummyString= dummyString.substring(0,4)
console.log( dummyString )

Output:-

Java

Example-2 of substring():-

let dummyString = 'Javascript*'
dummyString= dummyString.substring(-10,10)
console.log( dummyString )

Explanation:-

In the above code, the startIndex is treated as 0. The substring is formed from the beginning of the original string. Therefore substring(0,10).

Output:-

Javascript

Example-3 of substring():-

let dummyString = 'Javascript*'
dummyString= dummyString.substring(0,-10)
console.log( dummyString )

Explanation:-

In the above code, The endIndex is treated as 0. Therefore substring(0,0) , which returns nothing.

Output:-


Example-4 of substring():-

let dummyString = 'Javascript*'
dummyString= dummyString.substring(10,4)
console.log( dummyString )

Explanation:-

In the above code, The startIndex is greater than the endIndex. Therefore substring() method will swap both the arguments. Hence, substring(4,10).

Output:-

script

I hope this article helped you to understand the concept of the substring() method in javascript. Good Luck !!!

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top