Substring vs Substr vs Slice in JavaScript

Jun 20, 2019

The difference between the String#substring() and String#substr() functions is a common source of confusion. Even experienced JavaScript developers mix them up sometimes. There's also a third way to get a substring, the String#slice() function, that you may see in the wild. In this tutorial, you'll learn the difference between these 3 ways to get a substring in JavaScript.

String#substring()

The substring() function is the most common way to get a substring in JavaScript. It takes two parameters: indexStart and indexEnd. It returns the portion of the string that starts at indexStart and ends the character immediately preceding indexEnd. For example:

const str = 'Twas the night before Christmas';

let indexStart = 0;
let indexEnd = 4;
str.substring(indexStart, indexEnd); // 'Twas'

str.substring(5, 14); // 'the night'

If you don't specify indexEnd, the substring() function returns the rest of the string starting at indexStart.

str.substring(5); // 'the night before Christmas'

The substring() function has some quirky behavior in edge cases:

For example, substring(4, -1) is equivalent to substring(4, 0), which in turn is equivalent to substring(0, 4) as shown below.

str.substring(4, -1); // 'Twas'

String#substr()

The substr() function is also common, but it is considered a "legacy function" in Mozilla's docs. You shouldn't use it when writing new code, but you may see it in existing JavaScript projects.

The key difference between substring() and substr() is that substr() has a different 2nd parameter. The first parameter to substr() is start, and the 2nd is length. For example:

const str = 'Twas the night before Christmas';

let start = 0;
let length = 4;
// If `start === 0`, `substr()` and `substring()` are equivalent
str.substr(start, length); // 'Twas'

str.substr(5, 9); // 'the night'
'the night'.length; // 9

Unlike substring(), you can call substr() with a negative start. That will make substr() start counting at the end of the string as opposed to the beginning. For example:

const str = 'Twas the night before Christmas';

let start = -9;
let length = 9;
str.substr(start, length); // 'Christmas'

'Christmas'.length; // 9

String#slice()

The slice() function is less common than substring() and substr(). However, it has the best aspects of both substring() and substr(). Like substring(), the slice() function takes the start and end indices as parameters, and is not considered a legacy function. Like substr(), the slice() function supports negative indices. For example:

const str = 'Twas the night before Christmas';

str.slice(0, 4); // Twas
str.slice(5, 14); // the night
str.slice(-16, -10); // before
str.slice(-9); // Christmas

The slice() function seems like the clear winner out of the 3:


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials