tags:

views:

398

answers:

1

Does anyone know what is the difference between these two methods?

+7  A: 

slice() works like substring() with a few different behaviors.

Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);

Notes on substring():

  • If start equals stop, it returns an empty string.
  • If stop is omitted, it extracts characters to the end of the string.
  • If either argument is less than 0 or is NaN, it is treated as if it were 0.
  • If either argument is greater than string’s length, either argument will use string’s length.
  • If start > stop, then substring will swap those 2 arguments.

Notes on slice():

  • If stop is omitted, slice extracted chars to the end of the string, exactly like substring().
  • If start > stop, slice() will NOT swap the 2 arguments.
  • If start is negative, slice() will set char from the end of string, exactly like substr() in Firefox. This behavior is observed in both Firefox and IE.
  • If stop is negative, slice() will set stop to: (string.length – 1) – stop (original value).

Source: Rudimentary Art of Programming & Development: Javascript: substr() v.s. substring()

Daniel Vassallo