Slice, substr and substring in javascript

There is not much difference in the three of these. Each one of these need a start index as one of the parameters. To look into the syntax first, for each one of them:

Following are the examples that demonstrate different scenarios and would help you compare between the three.

Important points to note:

  1. substr sometimes can give you inconsistent results. For example, 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).
  2. substring swaps it’s parameters if the starting index is greater than the stopping index (start > stop).
  3. substring returns the entire string if the starting index is negative.
  4. slice extracts from the end of the string if the starting index is negative.

Among all the three, slice always outperforms for it’s better behavior across all the browsers and also never swaps irrespective of the start and stop values.


Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.