JavaScript substr(): Legacy String Method

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));

Legacy substr() Syntax Top ↑

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().

Extract from a Start Position to the End Top ↑

This preserves the first original example.

const text = "Welcome to www.plus2net.com";
console.log(text.substr(3));

Extract a Fixed Number of Characters Top ↑

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));

Negative start Values Top ↑

A negative start counts backward from the end.

const text = "JavaScript";
console.log(text.substr(-6)); // Script

substr() vs slice() vs substring() Top ↑

MethodArgumentsNegative indexesUse in new code
substr()start, lengthNegative start counts from endLegacy; avoid for new code
slice()start, endSupported; count from endRecommended
substring()start, endNegative values become 0Standard and supported

Migrating Existing substr() Code Top ↑

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

Common substr() Mistakes Top ↑

  • Using substr() for new cross-platform code when standard alternatives exist.
  • Confusing its second argument (length) with an end index.
  • Assuming a mechanical conversion to slice() is safe for every negative-value edge case.
  • Confusing substr() with substring() because of their similar names.

A practical legacy use case is shown in the email string-processing example.

String Reference substring()




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer