Cybercrux

Everything is achievable through technology

Slice, Substring, or Substr?

JavaScript: Slice, Substring, or Substr?

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!'

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s