Jack MooreTwitterGithub

JavaScript: Slice, Substring, or Substr?


Jun 25th, 2011

A comparison of substring methods.


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); // extracts 'news'

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

// substr
// syntax: string.substr(start [, length])
"Good news, everyone!".substr(5,4); // extracts '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:

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 You

Follow me on Twitter, Github, or RSS. Why should you? I'm meticulous and have a lot of free time. Sometimes good things come out of that.

Leave a Comment