The substring function in JavaScript is String.prototype.substring(), which returns a portion of a string between two indices. For example, 'Hello World'.substring(0, 5) returns 'Hello'. There are actually three similar methods—substring(), substr(), and slice()—and choosing the right one depends on your needs and browser support.
Background: Why Three Methods?
JavaScript has evolved over decades, and string extraction methods reflect that history. substring() and substr() were both introduced in the earliest versions of JavaScript (ECMAScript 1, 1997). slice() was added later with ECMAScript 3 (1999) as a more consistent method for arrays and strings. The existence of three similar methods often confuses beginners, but each has distinct behavior regarding negative indices and argument order. Understanding their differences helps you write cleaner, more predictable code.
How substring() Works
The substring() method takes two arguments: indexStart (required) and indexEnd (optional). It returns characters from indexStart up to, but not including, indexEnd. If indexEnd is omitted, it goes to the end of the string. Key behaviors:
- If
indexStartis greater thanindexEnd, the arguments are swapped. For example,'abcdef'.substring(4, 2)returns'cd'(same assubstring(2, 4)). - Negative arguments are treated as
0. So'abcdef'.substring(-2)returns'abcdef'. - Values greater than the string length are clamped to the string length.
Example with output:
let str = 'JavaScript';
console.log(str.substring(0, 4)); // 'Java'
console.log(str.substring(4)); // 'Script'
console.log(str.substring(4, 0)); // 'Java' (swapped)
How substr() Works (Deprecated)
The substr() method is deprecated and should not be used in new code. It takes start and length arguments, not end index. It behaves differently with negative start: negative values count from the end of the string. For example:
'Hello'.substr(1, 3); // 'ell'
'Hello'.substr(-3); // 'llo'
Because substr() is not part of the core ECMAScript specification (it was defined in Annex B for web browsers), it may not work in non-browser environments like Node.js (though it does in practice for compatibility). Modern best practice is to avoid it entirely and use slice() or substring().
How slice() Works and When to Prefer It
The slice() method is similar to substring() but with two important differences:
- Negative indices count from the end of the string.
'Hello'.slice(-3)returns'llo'. - If
startis greater thanend, it returns an empty string (no swapping).
Example:
'Hello World'.slice(0, 5); // 'Hello'
'Hello World'.slice(-5); // 'World'
'Hello World'.slice(5, 0); // ''
Prefer slice() when you need negative indexing or consistent behavior with arrays (since Array.prototype.slice() works the same way). It is fully standardized and supported everywhere.
How to Choose the Right Method
Here’s a quick decision guide:
- Need to extract from the end? Use
slice()with negative indices. - Need a substring between two positions? Use
substring()orslice()—both work, butslice()is more predictable if you might pass negative values. - Need to extract a fixed number of characters from a position? Use
substr()only if you must support ancient browsers; otherwise useslice()with computed end index:str.slice(start, start + length). - Working with arrays? Use
slice()to keep consistent syntax.
In modern JavaScript (ES6+), slice() is generally the recommended choice for its flexibility and clarity.
Common Problems and Misconceptions
One common mistake is confusing substring() and substr() arguments. Another is assuming negative indices work in substring()—they don’t; they’re treated as zero. Also, remember that strings are immutable; these methods return new strings and do not modify the original. A frequent bug is using substring() with swapped indices accidentally, which silently produces a different result than expected. For example, 'abcdef'.substring(3, 1) returns 'bc', not an error. If you need to throw an error on invalid input, consider validating manually.
Performance and Browser Support
In terms of performance, all three methods are highly optimized and differences are negligible for typical use. However, substr() is deprecated and may be removed in future versions, so using it risks future compatibility. All modern browsers (Chrome, Firefox, Safari, Edge) support substring() and slice() completely. For Node.js, both are fully supported. If you’re targeting very old environments (IE8 and earlier), substring() and substr() are safer, but for any modern project, slice() is the best choice.
Alternatives and Related Methods
Beyond these three, JavaScript offers other string methods that might suit specific needs:
charAt()– returns the character at a specific index.indexOf()/lastIndexOf()– find positions to use with substring methods.split()– breaks a string into an array, useful for extracting parts.replace()– replaces substrings with new content.- Regular expressions with
match()orexec()for pattern-based extraction.
For example, to extract everything after the last slash in a URL, you could use url.slice(url.lastIndexOf('/') + 1).
Frequently Asked Questions
What is the difference between substring and slice?
The main difference is how they handle negative indices. slice() treats negative indices as counting from the end, while substring() treats them as zero. Also, substring() swaps arguments if start > end, whereas slice() returns an empty string in that case.
Is substr deprecated? Should I use it?
Yes, substr() is officially deprecated in the ECMAScript specification (though still widely supported in browsers). It’s recommended to avoid it and use slice() or substring() instead for future-proof code.
How do I extract a substring from the end of a string?
Use slice() with a negative start index. For example, 'Hello World'.slice(-5) returns 'World'. If you need a specific length, use slice(-length) or slice(start, start + length).
Can I use substring with negative indices?
No, negative indices are treated as 0 in substring(). If you need negative indexing, use slice().
Which method is fastest?
Performance differences are negligible for most applications. All three methods are implemented natively and are highly optimized. Focus on correctness and readability rather than micro-optimizations.
Does substring modify the original string?
No, strings are immutable in JavaScript. All these methods return a new string, leaving the original unchanged.
Related
- Strings in R: Text, Character Vectors, and Examples
- Creating a Split Form in Access: Steps and Tips
- String Array Split in Java: Methods, Examples, and Tips
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel INDEX Array Formula: How It Works and When to Use ItIn Excel for Microsoft 365, INDEX can return a value from a range or return an array of…
- SUMIF Excel Cell Reference: Syntax, Examples, and FixesWith criteria in A2:A6 and amounts in C2:C6, enter =SUMIF(A2:A6,"North",C2:C6) to add the amounts for rows marked North;…
- XLOOKUP in Excel: What If the Return Cell Is Blank?If XLOOKUP finds a match whose return cell is truly empty, Excel normally displays 0—not a blank. With…
- Concatenate in Excel: Formulas, Delimiters, and TipsTo concatenate in Excel means to join text or values into one text string. In Microsoft Excel for…
- Filter in Excel With Blank Rows: Keep Records TogetherTo filter data that contains blank rows, select the entire data range—including the blank rows—and choose Data >…
- Excel Keyboard Shortcut to Paste Values Without FormulasIn Excel for Microsoft 365 on Windows, copy the cells, select the destination, then press Ctrl+Alt+V, press V,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.