String.prototype.substr() - JavaScript | MDN (original) (raw)

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The substr() method of String values returns a portion of this string, starting at the specified index and extending for a given number of characters afterwards.

Try it

const str = "Mozilla";

console.log(str.substr(1, 2));
// Expected output: "oz"

console.log(str.substr(2));
// Expected output: "zilla"

Syntax

substr(start)
substr(start, length)

Parameters

start

The index of the first character to include in the returned substring.

length Optional

The number of characters to extract.

Return value

A new string containing the specified part of the given string.

Description

A string's substr() method extracts length characters from the string, counting from the start index.

Although you are encouraged to avoid using substr(), there is no trivial way to migrate substr() to either slice() or substring() in legacy code without essentially writing a polyfill for substr(). For example, str.substr(a, l), str.slice(a, a + l), and str.substring(a, a + l) all have different results when str = "01234", a = 1, l = -2 — substr() returns an empty string, slice() returns "123", while substring() returns "0". The actual refactoring path depends on the knowledge of the range of a and l.

Examples

Using substr()

const aString = "Mozilla";

console.log(aString.substr(0, 1)); // 'M'
console.log(aString.substr(1, 0)); // ''
console.log(aString.substr(-1, 1)); // 'a'
console.log(aString.substr(1, -1)); // ''
console.log(aString.substr(-3)); // 'lla'
console.log(aString.substr(1)); // 'ozilla'
console.log(aString.substr(-20, 2)); // 'Mo'
console.log(aString.substr(20, 2)); // ''

Specifications

Specification
ECMAScript® 2026 Language Specification # sec-string.prototype.substr

Browser compatibility

See also