Open In App

JavaScript String substring() Method

Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript string.substring() is an inbuilt function in JavaScript that is used to return the part of the given string from the start index to the end index. Indexing starts from zero (0). 

Syntax: 

string.substring(Startindex, Endindex);

Parameters:

  • Startindex: describe the part of the string to be taken as a substring
  • Endindex: describe the part of the string to be taken as a substring(optional). 

Return value:

It returns a new string that is part of the given string. 

Example 1: This example prints the values of the sub-strings from a variable string in the console, here we use starting index value.

javascript




const str = "GeeksforGeeks";
const result = str.substring(8);
console.log(result);


Output

Geeks

Example 2: In this example, we are using starting and last index values.

Javascript




const str = "GeeksforGeeks";
const result = str.substring(5, 8);
console.log(result);


Output

for

Example 2: Index always starts with 0. If still, we take an index as negative, it will be considered zero and the index can’t be in fractions if it is found so, it will be converted into its just a lesser whole number. 

javascript




// Taking a string as letiable
let string = "geeksforgeeks";
a = string.substring(-1)
b = string.substring(2.5)
c = string.substring(2.9)
 
// Printing new string which are
// the part of the given string
console.log(a);
console.log(b);
console.log(c);


Output

geeksforgeeks
eksforgeeks
eksforgeeks

We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.

Supported Browser:

  • Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Internet Explorer 3 and above
  • Opera 3 and above
  • Safari 1 and above


Last Updated : 29 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments