substr() extracts part of a string using a starting index and a character count. It is retained here for understanding existing code, but it is a legacy JavaScript feature; prefer slice() or substring() in new code.
const text = "Welcome to www.plus2net.com";
console.log(text.substr(3, 7));
string.substr(start)
string.substr(start, length)
The second argument is a length, not an ending index. That is the main difference from slice() and substring().
This preserves the first original example.
const text = "Welcome to www.plus2net.com";
console.log(text.substr(3));
The original tutorial also uses a start position of 3 and a length of 7.
const text = "Welcome to www.plus2net.com";
console.log(text.substr(3, 7));
A negative start counts backward from the end.
const text = "JavaScript";
console.log(text.substr(-6)); // Script
| Method | Arguments | Negative indexes | Use in new code |
|---|---|---|---|
substr() | start, length | Negative start counts from end | Legacy; avoid for new code |
slice() | start, end | Supported; count from end | Recommended |
substring() | start, end | Negative values become 0 | Standard and supported |
For straightforward non-negative values, text.substr(start, length) can often be rewritten as text.slice(start, start + length). Do not perform that replacement blindly when negative or unusual values are possible because the methods have different edge-case rules.
const text = "JavaScript";
const start = 4;
const length = 6;
console.log(text.slice(start, start + length)); // Script
substr() for new cross-platform code when standard alternatives exist.slice() is safe for every negative-value edge case.substr() with substring() because of their similar names.A practical legacy use case is shown in the email string-processing example.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.