How to work Substring method in JavaScript

Posted By : Vinay Tiwari | 28-Dec-2017

In this blog, we will be learning about Substring method in javascript. 3 methods in javascript that can be used to recover a substring from a given string substring(), substr(), slice()

substring() method: This method has 2 parameters namely start and end.The start parameter is a required one and defines the position from where to start the extraction.The end parameter is considered to be optional and defines the position where the extraction is expected to end. The character at the end position of the string is not included in the substring.

If the end parameter is not mentioned then all the characters from the starting position to the ending position of the string are extracted.

And if the value of the start parameter is more than the value of the end parameter, this method will swap the two arguments. Which means that the start value will be used as an end and end value will be used as the start.

Let's look at an example :-

Extract the first 10 characters

var str = "JavaScript Blog"
var result = str.substring(0, 10);
console.log(result) // JavaScript

 

Here within this variable str we have the strng "JavaScript Blog" and that we are calling substring() method. we passed the two parameters 0 as the start parameter and 10 as the end parameter. Now, the index position within string starts with 0 that means at index position 0 we have this letter 'J' and at index position 2 we have this letter 'a' and so on. 

If the value of the start parameter is greater than the value of the end parameter, this method will swap the two arguments. This means start will be used as end and end will be used as a start.

var str = "JavaScript Blog" 
var result = str.substring(10, 0);
console.log(result) // JavaScript

 

 

substr() method: This method has two parameters start and count. start parameter is required and specifies the position where to start the extraction. count parameter is optional and specifies the number of characters to extract.

If the count parameter is not specified, all the characters from the start position till the end of the string are extracted. If the count is 0 or negative, an empty string is returned.

for example :-

var str = "JavaScript Blog" 
var result = str.substring(11);
console.log(result) // Blog

 

in this example, start parameter is 11 and count parameters are optional.

 

Thanks

 

About Author

Author Image
Vinay Tiwari

Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.

Request for Proposal

Name is required

Comment is required

Sending message..