The Wayback Machine - https://web.archive.org/web/20250118103836/https://www.geeksforgeeks.org/javascript-string-substring-method/
Open In App

JavaScript String substring() Method

Last Updated : 28 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The substring() method in JavaScript is used to extract characters between two indices from a string, without modifying the original string. This method returns a new string that is a part of the original string, starting from a specified position up to (but not including) another specified position.

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. 
JavaScript
let s = "Hello, World!";

// Extract substring from index 7 to index 12
let res = s.substring(7, 12);

console.log(res); 

Output
World
  • Starting Index: The substring begins at index 7 (‘W’).
  • Ending Index: The substring ends at index 12 (but does not include the character at index 12, which is ‘!’).
  • In this case, substring(7, 12) extracts the portion of the string from index 7 to index 11, resulting in “World”.

Extracting Substrings by Character Index

One common use case for substring() is when you need to extract specific substrings from a known index range. For example, you might extract the first name or last name from a full name string.

JavaScript
let s1 = "Amit Ray";
let s2 = s1.substring(0, 4);
let s3 = s1.substring(5);

console.log(s2);
console.log(s3);

Output
Amit
Ray

Extracting a Portion of a URL

You can use substring() to extract parts of a URL, such as the protocol, domain, or path.

JavaScript
let url = "https://www.geeksforgeeks.org/javascript";
let domain = url.substring(8, 29); // Extract the domain
let path = url.substring(29);      // Extract the path

console.log(domain);
console.log(path);

Output
www.geeksforgeeks.org
/javascript

String Validation

substring() can be used in string validation checks, such as checking whether a specific portion of a string matches a pattern.

JavaScript
let email = "user@example.com";
let domain = email.substring(email.indexOf('@') + 1);

console.log(domain);

Output
example.com

Removing a Prefix or Suffix

If you need to remove a prefix or suffix from a string, you can use substring() to extract the part of the string that remains.

JavaScript
let fName = "report.pdf";
let ext = fName.substring(fName.lastIndexOf('.') + 1);

console.log(ext); 

Output
pdf

Handling Negative Indices

Unlike some other methods, substring() treats negative indices as 0. It does not count from the end of the string. Instead, it converts negative values to 0, meaning the method starts from the beginning of the string.

JavaScript
let s = "Hello, World!";
let res = s.substring(-5, -1);

console.log(res);

Output

This will result an empty string.

When the Starting Index is Greater

If the starting index is greater than the ending index, the substring() method swaps the values of the indices internally. This makes it easy to extract the substring regardless of the order of indices.

JavaScript
let s = "Learning JavaScript";
let res = s.substring(13, 8);

console.log(res);

Output
 Java

Using Only the Starting Index

If only the starting index is provided, substring() will return the substring from that index to the end of the string.

JavaScript
let s = "JavaScript is amazing!";
let res = s.substring(11);

console.log(res);

Output
is amazing!

Immutability

Like most string methods in JavaScript, substring() does not alter the original string. Instead, it returns a new string.

JavaScript
let s1 = "I love coding";
let s2 = s1.substring(2, 6);

console.log(s1);
console.log(s2); 

Output
I love coding
love

When to Use substring() in JavaScript

  • When You Know the Exact Indices: substring() is most useful when you know the exact indices of the portion of the string you want to extract. If the range of characters is fixed, this method provides a clean and simple solution.
  • For Extracting Static Portions of a String: If you need to extract specific static portions of a string—such as a certain section of a file name, URL, or user input—substring() is an ideal choice.
  • To Handle Cases with Uncertain Index Order: substring() is useful when the order of the start and end indices is not guaranteed. It automatically handles cases where the starting index is larger than the ending index, swapping them for you.
  • When Immutability is Important: Since substring() does not modify the original string, it is perfect for use cases where you need to retain the original string and work with substrings separately.

JavaScript String substring() Method- FAQs

How does the split() method work?

The split() method searches the string for the specified separator, divides the string at each occurrence of the separator, and returns an array of substrings. If the separator is not found, the entire string is returned as the only element of the array.

What happens if the separator is not found in the string?

If the separator is not found in the string, the split() method returns an array containing the entire string as its only element.

What happens if the limit is specified?

If the limit is specified, the split() method splits the string into the specified number of elements. For example, “a,b,c,d”.split(“,”, 2) returns [“a”, “b”].

Does the split() method modify the original string?

No, the split() method does not modify the original string. It returns a new array with the substrings, leaving the original string unchanged.

What are some common use cases for the split() method?

Common use cases for the split() method include:

  • Dividing sentences into words.
  • Parsing CSV or other delimited data.
  • Splitting strings based on patterns, such as whitespace or punctuation.
  • Extracting parts of a URL or file path.

Become an expert in solving problems with DSA JavaScript—the course designed to teach you Data Structures and Algorithms using JavaScript. Over the next 90 days, dive deep into key DSA concepts, learn to optimize your code, and gain hands-on experience solving challenging problems. Whether you're a beginner or looking to refine your JavaScript skills, this course will provide the knowledge you need to succeed.
Take on the Three 90 Challenge today! Complete 90% of the course within 90 days, and you’ll earn a 90% refund. This challenge is your chance to stay motivated, improve your skills, and get rewarded for your progress. Don’t wait—start your journey to DSA mastery with JavaScript today!


Next Article

Similar Reads

three90RightbarBannerImg