JavaScript: Slice, Substring, or Substr?

A comparison of substring methods.


June 25, 2011

In JavaScript, substrings are primarily extracted through one of following String methods: slice, substring, substr.

// slice 
// syntax: string.slice(start [, stop])
"Good news, everyone!".slice(5,9); 
// 'news'

// substring 
// syntax: string.substring(start [, stop])
"Good news, everyone!".substring(5,9); 
// 'news'

// substr
// syntax: string.substr(start [, length])
"Good news, everyone!".substr(5,4); 
// 'news'

All three of these methods take in a start index and an optional stop index (or length) parameter, but they differ in some important ways:

Negative start index

"Good news, everyone!".substring(-4);
// "Good news, everyone!"

"Good news, everyone!".substr(-4);
// "one!" modern browsers, including IE9
// "Good news, everyone!" IE8 and lower

"Good news, everyone!".slice(-4); 
// "one!"

Since all three methods have roughly equivalent performance, my preference is to use slice. It supports extracting from the end of the string and I feel that returning an empty string when start index > stop follows the principle of least surprise better than substring's swapping of parameters. I avoid substr because of the browser inconsistency.


Hey,

Follow me on Twitter and Github, that's where I'm most active these days. I welcome email (), but I'm afraid I no longer have time to answer personal requests for help regarding my plugins or posts. Thanks!