JavaScript: Slice, Substring, or Substr?
June 25, 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:
- substr can give inconsistent results. If the starting index is negative, substr will either return the whole string (Internet Explorer) or extract from the end of the string (other browsers).
- substring swaps it's parameters if the starting index is greater than the stopping index (start > stop).
- substring returns the entire string if the starting index is negative.
- slice extracts from the end of the string if the starting index is negative.
Good news, everyone!".slice(-4); // extracts '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!