Skip to content

substring and substr String Methods

substring(start, end) returns the characters from start up to, but not including, end. If end is left out, it runs to the end of the string. It does the same job as slice(), but treats unusual arguments differently. substr(start, length) is an older method that takes a length instead of an end position, and it is deprecated.

The example uses a product code made of three parts.

const code = 'GB-LON-0042';
console.log(code.substring(3, 6));
console.log(code.substring(7));
console.log(code.substring(6, 3));
console.log(code.substring(-4));

This prints:

LON
0042
LON
GB-LON-0042

The last two lines show the quirks. When start is greater than end, substring() swaps them. A negative argument, or NaN, is treated as 0, so substring(-4) returns the whole string.

slice() takes the same arguments but treats a negative position as a count back from the end of the string. It does not swap its arguments, so a start after end gives an empty string.

const code = 'GB-LON-0042';
console.log(code.slice(3, 6));
console.log(code.slice(-4));
console.log(code.slice(-4, -2));
console.log(JSON.stringify(code.slice(6, 3)));

This prints:

LON
0042
00
""

Counting from the end is often what is wanted, such as the last four digits of a code or the extension of a file name. slice() also matches the array method of the same name, so it is the better default. substring() is still fine where its swapping is useful or where the arguments are known to be in order.

substr(start, length) counts length characters from start, and accepts a negative start. It still works in every browser and in Node.js, but the language specification lists it only in an annex of legacy features kept for old web pages, and MDN marks it as deprecated. New code should use slice() instead.

const code = 'GB-LON-0042';
console.log(code.substr(3, 3));
console.log(code.substr(-4, 2));
const start = 3;
const length = 3;
console.log(code.slice(start, start + length));

This prints:

LON
00
LON

To replace substr(start, length), write slice(start, start + length). That rule breaks when start is negative and start + length comes to 0 or more, because the end position then falls before the start and slice() returns an empty string. For a negative start it is clearer to write both ends as counts from the end, so substr(-4, 2) becomes slice(-4, -2).

MDN has the full rules for substring and slice.

Steve Griffith covers this topic in his video substring and substr String methods.