Working with strings is a core part of being a web developer. From managing forms, handling user input, or cleaning up data, the use cases are many. Luckily, JavaScript provides a built-in substring()
method, which is designed to manipulate strings dynamically with ease.
In this blog, we will discuss what the substring()
method is, its syntax, real-world use cases, and much more. By the end, you will learn how to use the JavaScript substring()
method to solve many real-world problems.
Table of Contents
What is JavaScript substring()?
The substring()
method is used to extract a portion of text between two specified indices. It returns a new string without modifying the original, making it a safe and effective way to manipulate JavaScript strings.
Syntax:
str.substring(startIndex, endIndex)
Parameters:
- startIndex (required): The position where the extraction begins (zero-based index).
- endIndex (optional): The position where the extraction ends, but not including the character at this index. If omitted, the substring continues to the end of the string.
How substring() Method in JavaScript Works – Explained with Examples
The substring()
method in JavaScript can be used in multiple ways depending on the task at hand. Let’s explore how we can apply it effectively for different problems.
Output:
Inte
In this example, the substring()
method is used to extract characters starting from index 0 up to, but not including, index 4.
Example 2: Using only one parameter
Output:
ipaat
If you only provide one parameter to the substring()
method, JavaScript will consider that the first index and return the characters from that index to the end of the string.
Example 3: When startIndex is greater than endIndex
Output:
tell
When the first index provided is larger than the second, JavaScript will swap the values internally. So, substring(6,2)
becomes substring(2,6)
.
Example 4: Passing the Same Start and End Index
Output:
""
If both the parameters passed to the substring()
method are equal, no characters will be extracted and an empty string will be returned.
Example 5: Using Non-integer or Invalid Values
Output:
Intel
If a non-numeric value is passed as an index, JavaScript will convert them to numbers. Let’s move on to some real-world use cases so that you can get a better understanding.
Real-World Use Cases of JavaScript substring() Function
Now that you understand the basic syntax and behaviour of the substring()
method, let’s explore how you can apply it to everyday coding problems.
1. Extracting an Email Domain
Let’s say that you need to extract the domain name from a user’s email address. You can easily use the substring()
method to solve this problem.
Code:
Output:
example.com
As you can see from the code, we are extracting everything after the “@” in the email address, which will always contain the domain name. Try to use the same method to complete this exercise by further manipulating the output of this to remove the “.com”.
2. Generating Preview Text
The substring()
method can also be used to create small previews of text that you can use to convey a short intro to users. This is usually used for blogs, news apps, or social feeds.
Code:
Output:
JavaScript is a versatile and …
We are limiting the number of characters displayed to 30 characters and adding “…” to convey to the user that this is a preview. This approach is perfect for trimming long strings while maintaining readability.
3. Removing Prefixes or Suffixes
Let’s say you have a product ID like “ID-12345” and you want to remove the “ID-” prefix.
Code:
Output:
12345
In this example, we know that the first 3 characters are the ones we need to remove. And so we are using the substring()
method to display the string only after the first 3 characters.
Need to isolate part of a URL for routing or display? This is also possible with a simple use of the substring()
method.
Code:
Output:
javascript-substring
If you want to limit a username input to the first 10 characters:
Output:
superlongu
Edge Cases and Behavior of substring() Method in JavaScript
While substring()
is easy to use, there are a few quirks and edge cases you should be aware of to avoid unexpected results in your code.
1. When startIndex > endIndex
It is important to note that if the provided startIndex is greater than the endIndex, JavaScript swaps them internally so that it makes sense.
Code:
Output:
elli
You can see from the output that JavaScript has flipped the values and displayed the output starting from the 4th character (index 3) to the 8th (index 7).
2. What if Parameters are Omitted?
When you only provide one index, JavaScript will consider that the startIndex and return the values from that index to the end of the string.
Code:
Output:
llipaat
3. Using the Same Start and End Index
If both the startIndex and the endIndex are the same, JavaScript will print an empty string.
Code:
Output:
""
4. Negative Values Are Treated as Zero
Unlike slice(), which supports negative indices, substring()
converts any negative value to 0.
Code:
Output:
Inte
5. Non-Numeric Values Are Converted to 0
Passing a non-numeric or invalid value results in a fallback to zero.
Code:
Output:
Inte
6. Immutability of Strings
The method returns a new string. The original string remains unchanged.
Code:
Output:
Intellipaat
Inte
Difference Between substr(), slice() and substring() in JavaScript
Now that we have a solid understanding of substring()
and how to use it, let’s have a look at how it differs from slice() and substr(), which are also JavaScript string methods used to manipulate strings.
slice() vs substring() vs substr()
Feature | substring(start, end) | slice(start, end) | substr(start, length) |
Second argument | End index (non-inclusive) | End index (non-inclusive) | Length of characters |
Swaps indices? | Yes (if start > end) | No | No |
Negative indices | Treated as 0 | Counts from end | Counts from end |
Original string | Not modified | Not modified | Not modified |
Availability | Standard | Standard | Deprecated (avoid using) |
When to Use Which JavaScript String Function
- Use
substring()
for basic extraction when working with positive indices.
- Use slice() when you need negative indexing or more flexibility.
- Avoid substr() as it’s deprecated.
Even though the JavaScript substring()
function is an easy and lightweight way to work with strings, when using it in a large-scale application, it is important to keep in mind some performance considerations.
1. Fast for Small to Medium Strings
For short strings or infrequent operations, substring()
is extremely fast and efficient. Modern JavaScript engines optimize string slicing methods well, so there’s typically no noticeable lag.
Code:
Output:
hello
2. Immutable Strings
Strings in JavaScript are immutable, meaning they cannot be changed later on. So, the substring()
method returns a new string without changing the original.
Code:
Tip: Avoid excessive substring operations in performance-critical loops.
3. Prefer slice() for End-Based Operations
For accessing the last characters of a string, for example, the last four, the slice() method is a more appropriate approach.
Code:
Output:
12345
In most real-world scenarios, substring()
is perfectly performant. But being mindful of string immutability and avoiding overuse in loops helps you write more optimized, scalable code.
Practice Exercises for JavaScript substring()
Now it’s time to apply what you have learned in this blog to solve some problems on your own.
Code:
Try to complete the code above using what you have learned so far. The output should be “John”.
Exercise 2: Get the Last 4 Digits of a String
Code:
Expected Output: “2024”
Hint: You’ll need to use indexOf(“-“) and maybe add 1 to skip the dash.
Conclusion
The substring()
method in JavaScript is a simple yet powerful tool for extracting specific parts of a string. While modern JavaScript gives you multiple ways to slice and dice strings, substring()
remains a reliable choice for many everyday scenarios, especially when working with clean, index-based logic. Looking to deepen your JavaScript and web development skills? Our full-stack development course can help you go beyond tutorials with real-world projects.
JavaScript Substring: Methods and Examples – FAQs
1. What is the difference between substring()
and slice()?
Both the substring()
and slice() methods are used in JavaScript to work with strings. But they function in different ways:
substring()
swaps indices if the first is greater than the second; slice() does not.
- slice() supports negative indices;
substring()
treats them as 0.
- Both return a new string and do not modify the original.
2. Can I use negative numbers with substring()
?
No, if you input a negative number into the parameters of a substring()
, it will be treated as 0.
3. Does substring()
modify the original string?
No, since strings in JavaScript are immutable, substring()
, just like the other methods, returns a new string.
4. What happens if I pass non-numeric values?
JavaScript tries to coerce non-numeric values to numbers. If the coercion fails (e.g., you pass a string that can’t be converted), it defaults to 0.
5. Is substr() the same as substring()
?
No. substr() uses a length for its second parameter, while substring()
uses an end index. Also, substr() is deprecated and should be avoided in modern JavaScript.