The JavaScript string.substring() method
The substring() method returns the part of a string between a start and end index. "JavaScript".substring(0, 4) gives "Java". It's very similar to slice(), with two differences: it treats negative indices as 0, and it swaps the arguments if start is greater than end. For most code, slice() is the simpler choice.
Overview
substring() extracts a chunk of a string between two positions — the character at start up to, but not including, end. "hello".substring(1, 3) returns "el". Leave off the end and it runs to the finish of the string. On the surface it does the same job as slice().
The differences are in the edge cases, and they're the reason most developers prefer slice(). First, substring() treats negative indices (and NaN) as 0, so substring(-3) doesn't count from the end — it returns the whole string. Second, if you pass arguments in the "wrong" order with start > end, substring() quietly swaps them rather than returning an empty string.
Those behaviors are occasionally convenient but more often surprising. The practical guidance: use slice() as your default for extracting substrings, since it supports negative indices and behaves predictably. Reach for substring() mainly when you specifically want its argument-swapping forgiveness. (The third option, substr(), is deprecated — avoid it.)
Syntax
str.substring(indexStart)
str.substring(indexStart, indexEnd)
"JavaScript".substring(0, 4) // "Java"
"JavaScript".substring(4) // "Script"
"abc".substring(2, 0) // "ab" (args swapped)
Parameters
The string.substring() method accepts the following parameters.
| Parameter | Description |
|---|---|
indexStart |
Index of the first character to include. Negative values are treated as 0. |
indexEnd |
Optional. Index to stop before (not included). Defaults to the string length. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const code = 'ABC-1234';
const prefix = code.substring(0, 3);
const number = code.substring(4);
document.getElementById('out').textContent =
'prefix: ' + prefix + '\n' +
'number: ' + number; // prefix: ABC / number: 1234
</script>
Best practices
- Prefer slice() as your default — it supports negative indices and behaves predictably.
- Use
substring()when you actually want its argument-swapping leniency. - Remember it treats negative indices as
0, so it can't count from the end. - Avoid the deprecated
substr()entirely.
Frequently asked questions
What is the difference between substring() and slice()?
substring() treats negatives as 0 and swaps the arguments if start > end. slice() is the more predictable default.Does substring() support negative indices?
0. Use slice() to count from the end.Why did substring() swap my arguments?
start is greater than end, substring() swaps them so it never errors. That's expected behavior, not a bug.