JavaScript substring() Method: Variants and Uses

The substring() method in JavaScript extracts parts of a string between specified indices. This article explores its syntax, usage, key differences from similar methods like slice(), and practical applications such as extracting usernames or file extensions. Try hands-on exercises to master string manipulation.

JavaScript provides several methods to manipulate strings, and the substring() method is one of the most commonly used. It allows developers to extract a portion of a string based on specified indices. Understanding how substring() works, along with its variants, can help in efficient string manipulation.

What is the substring() Method in JavaScript?

The substring() method in JavaScript extracts characters from a string between two specified indices. It does not modify the original string but returns the extracted portion as a new string.

What is the substring() Method in JavaScript?

Syntax:

string.substring(startIndex, endIndex)

Parameters:

  • startIndex (required) – The starting position of extraction (0-based index).
  • endIndex (optional) – The position up to (but not including) which characters are extracted. If omitted, the method extracts until the end of the string.

Return Value:

A new string containing the extracted portion of the original string.

Understand Datatypes in JavaScript and how they impact variable behavior, memory usage, and data manipulation in modern web development.

Examples of substring() Usage

1. Basic Example

let text = "JavaScript";
let result = text.substring(0, 4);
console.log(result); // Output: "Java"

2. Omitting the endIndex

let text = "Hello, World!";
let result = text.substring(7);
console.log(result); // Output: "World!"

3. Swapping Indices

If startIndex is greater than endIndex, JavaScript automatically swaps them.

let text = "JavaScript";
let result = text.substring(4, 0);
console.log(result); // Output: "Java"

4. Handling Negative Values

let text = "Example";
let result = text.substring(-3, 4);
console.log(result); // Output: "Exam"

5. Extracting a Middle Portion of a String

let sentence = "JavaScript is a powerful language.";
let extracted = sentence.substring(11, 21);
console.log(extracted); // Output: "is a power"

substring() vs slice()

Both substring() and slice() extract parts of a string, but they have key differences:

Featuresubstring()slice()
Handles negative indicesConverts them to 0Interprets them as offsets from the end
Swaps start and end indicesYesNo
Modifies original stringNoNo

Example Comparison

let text = "JavaScript";
console.log(text.substring(-3, 4)); // Output: "Java"
console.log(text.slice(-3, 4));     // Output: ""

Practical Applications of substring()

1. Extracting a Username from an Email

let email = "user@example.com";
let username = email.substring(0, email.indexOf("@"));
console.log(username); // Output: "user"

2. Extracting File Extensions

let filename = "document.pdf";
let extension = filename.substring(filename.lastIndexOf(".") + 1);
console.log(extension); // Output: "pdf"

3. Shortening Strings for Display

let text = "This is a long string that needs to be shortened.";
let shortText = text.substring(0, 20) + "...";
console.log(shortText); // Output: "This is a long strin..."

4. Extracting a Domain Name from a URL

let url = "https://www.example.com";
let domain = url.substring(url.indexOf("www."), url.indexOf(".com") + 4);
console.log(domain); // Output: "www.example.com"

Practice Exercises

To solidify your understanding, try solving these exercises:

1. Extract the first word from a sentence:

let sentence = "Learning JavaScript is fun!";
let firstWord = sentence.substring(0, sentence.indexOf(" "));
console.log(firstWord); // Expected output: "Learning"

2. Extract the last three characters of a string:

let text = "JavaScript";
let lastThree = text.substring(text.length - 3);
console.log(lastThree); // Expected output: "ipt"

3. Extract the middle part of a string dynamically:

let text = "CodingIsAwesome";
let middlePart = text.substring(3, text.length - 3);
console.log(middlePart); // Expected output: "ingIsAwe"

4. Extract a specific portion of a URL path:

let path = "/users/profile/settings";
let extractedPath = path.substring(path.indexOf("profile"), path.indexOf("settings") - 1);
console.log(extractedPath); // Expected output: "profile"

Conclusion

The substring() method is a simple yet powerful tool for extracting portions of a string in JavaScript. Understanding its behavior, differences from slice(), and real-world applications can help developers write cleaner and more efficient code.

By leveraging this method appropriately, you can handle string operations with greater flexibility and control.

To enhance your JavaScript skills, check out the Free JavaScript Courses offered by Great Learning Academy.

These courses cover everything from the basics to advanced topics like object-oriented programming and interactive website creation. Enroll now to gain hands-on experience and earn certificates.

Frequently Asked Questions(FAQ’s)

1. Can substring() be used with template literals in JavaScript?
Yes, you can use substring() with template literals. Since template literals are just strings, you can call .substring() on them like any other string.

let str = `Hello, JavaScript!`;
console.log(str.substring(7, 17)); // Output: "JavaScript"

2. What happens if startIndex and endIndex are the same?
If startIndex and endIndex are the same, the substring() method returns an empty string.

let text = "Example";
console.log(text.substring(3, 3)); // Output: ""

3. Is substring() case-sensitive?
Yes, substring() is case-sensitive because it simply extracts characters without modifying them.

let text = "JavaScript";
console.log(text.substring(4, 10)); // Output: "Script" (preserves case)

4. Can substring() be chained with other string methods?
Yes, substring() can be chained with other string methods like toUpperCase() or trim().

let text = "  Hello, JavaScript!  ";
let result = text.substring(2, 14).trim().toUpperCase();
console.log(result); // Output: "HELLO, JAVASC"

5. Does substring() work with non-English characters or emojis?
Yes, but it treats each Unicode character as a single unit, which may lead to unexpected results with emojis or special characters.

let emojiString = "Hello 😊 World!";
console.log(emojiString.substring(6, 8)); // Output: "😊 " (May not work as expected with multi-byte characters)

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top