The JavaScript substring() method extracts characters from a string between two specified indices and returns them as a new string, without modifying the original. For example, 'Hello World'.substring(0, 5) returns 'Hello'.
What Is substring() and Why Use It?
JavaScript strings are sequences of UTF-16 code units, and substring() is one of the built-in methods to slice out a portion of that sequence. It is a fundamental tool for tasks like parsing user input, extracting substrings from URLs, or formatting text. Unlike some other languages, JavaScript strings are immutable, so substring() never alters the original string; it always returns a fresh string.
The method takes two parameters: start (required) and end (optional). If end is omitted, it extracts to the end of the string. The returned substring includes the character at the start index but excludes the character at the end index. This is a common source of off-by-one errors for beginners.
How substring() Works Under the Hood
Understanding the exact behavior of substring() helps avoid surprises. Here are the key rules:
- If
startis greater thanend, the arguments are swapped. For example,'abcdef'.substring(4, 2)returns'cd'(same assubstring(2, 4)). - If either argument is negative, it is treated as
0. So'abcdef'.substring(-2, 3)returns'abc'. - If either argument is
NaN, it is treated as0. - If
startis greater than the string length, it is set to the string length (so you get an empty string). - If
endis greater than the string length, it is set to the string length.
These rules make substring() forgiving, but they also mean you cannot use negative indices to count from the end, unlike slice().
substring() vs slice() vs substr()
JavaScript offers three similar methods: substring(), slice(), and the deprecated substr(). Knowing the differences is crucial for writing correct code.
substring(start, end): Swaps arguments ifstart > end; treats negative values as0.slice(start, end): Does not swap; supports negative indices to count from the end. For example,'abcdef'.slice(-3, -1)returns'de'.substr(start, length): The second parameter is the length of the substring, not an end index. It is deprecated and should not be used in new code.
For most modern code, slice() is preferred because its behavior is more intuitive and it supports negative indices. However, substring() is still widely used and perfectly valid.
How to Choose the Right Method
When deciding which method to use, consider the following:
- If you need to extract from the end of the string (e.g., last 4 characters), use
slice(-4). - If you know the start and end indices and want to avoid accidental swapping, use
slice(). - If you are working with legacy code or specifically need the swapping behavior,
substring()is fine. - Never use
substr()in new code; it is deprecated and may be removed in future versions.
Here is a quick comparison table (in your mind):
'Hello'.substring(1, 3)→'el''Hello'.slice(1, 3)→'el''Hello'.substr(1, 3)→'ell'
Common Mistakes and Pitfalls
Even experienced developers occasionally trip over these subtle behaviors:
- Assuming the end index is inclusive: Remember,
substring(0, 5)gives characters at indices 0–4, not 0–5. - Using negative indices expecting them to work like
slice():substring(-3)returns the entire string because -3 becomes 0. - Forgetting that
substring()does not modify the original string: If you need to update a variable, you must assign the result. - Confusing
substr()withsubstring(): The second argument means different things.
Another common misconception is that substring() is faster than slice(). In practice, performance differences are negligible for typical use cases; readability matters more.
Practical Examples in Real Code
Let’s see substring() in action with common scenarios:
- Extracting a domain from a URL:
const url = 'https://example.com/path'; const domain = url.substring(url.indexOf('//') + 2, url.indexOf('/', url.indexOf('//') + 2));This yields'example.com'. - Getting a file extension:
const filename = 'report.pdf'; const ext = filename.substring(filename.lastIndexOf('.') + 1);Returns'pdf'. - Truncating a long string:
function truncate(str, max) { return str.length > max ? str.substring(0, max) + '…' : str; }
These examples show how substring() integrates with other string methods like indexOf() and lastIndexOf().
Performance and Alternatives
For most applications, substring() is more than fast enough. However, if you are processing extremely large strings in a loop, consider these alternatives:
- String concatenation: Building a new string piece by piece can be slower due to immutability, but modern engines optimize it well.
- Array methods: Splitting a string into an array with
split()and then joining can be useful for complex transformations, but it is heavier. - Regular expressions: For pattern-based extraction,
match()orreplace()might be more appropriate.
In terms of memory, substring() creates a new string, so using it repeatedly on huge strings can increase garbage collection. But this is rarely a bottleneck in real-world code.
Frequently Asked Questions
Does substring() change the original string?
No. Strings are immutable in JavaScript, so substring() returns a new string and leaves the original untouched. If you want to update a variable, you must reassign it: str = str.substring(1, 5).
What is the difference between substring() and slice()?
Both extract a portion of a string, but slice() supports negative indices (counting from the end) and does not swap arguments if start is greater than end. substring() treats negative values as 0 and swaps arguments. For example, 'abcde'.slice(-3) returns 'cde', while 'abcde'.substring(-3) returns 'abcde'.
Can I use substring() with negative indices?
Yes, but they are treated as 0. So 'hello'.substring(-2, 3) is the same as 'hello'.substring(0, 3) and returns 'hel'. If you need to count from the end, use slice() instead.
Is substr() the same as substring()?
No. substr() takes a start index and a length, while substring() takes start and end indices. For example, 'hello'.substr(1, 3) returns 'ell', but 'hello'.substring(1, 3) returns 'el'. substr() is deprecated and should be avoided.
What happens if start is greater than end in substring()?
JavaScript swaps the two arguments. So 'abcdef'.substring(4, 2) is equivalent to 'abcdef'.substring(2, 4) and returns 'cd'. This is different from slice(), which would return an empty string in that case.
How do I extract the last N characters of a string?
Use slice(-N) for clarity, because substring() cannot handle negative indices. For example, 'Hello World'.slice(-5) returns 'World'. If you must use substring(), you can calculate the start index manually: str.substring(str.length - 5).
Related
- Split a String in C++: Methods and Examples
- String to Int in C++: Safe Conversion Methods
- Split in Oracle SQL: Turn Delimited Text Into Rows
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- What Is a Split Queen Sheet? Size and Fit ExplainedA split queen sheet is bedding made for a queen-size bed whose sleeping surface is divided into two…
- Data Validation and Verification in Excel ExplainedData validation checks whether data follows defined rules, while data verification checks whether it is accurate and matches…
- Cover Page in Word: How to Add and Customize ItTo add a cover page in Microsoft Word for Microsoft 365 on Windows, place the cursor anywhere in…
- How to Get Rid of Mail Merge in Word Without Losing TextTo get rid of mail merge in Word, first save a copy, then choose what should happen to…
- SQL String Split: How to Separate Delimited ValuesTo split a delimited string into rows, use the function supported by your database: SQL Server has STRING_SPLIT,…
- Excel 5 Student’s Book: Is It Really for Grade 5 Students?If you mean a book titled Excel 5 Student’s Book, the name alone does not confirm that it…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.