slice() works like substring() with a few different behaviors.
Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);
What they have in common:
- If
startequalsstop: returns an empty string - If
stopis omitted: extracts characters to the end of the string - If either argument is greater than the string’s length, the string’s length will be used instead.
Distinctions of substring():
- If
start > stop, thensubstringwill swap those 2 arguments. - If either argument is negative or is
NaN, it is treated as if it were0.
Distinctions of slice():
- If
start > stop,slice()will return the empty string. ("") - If
startis negative: sets char from the end of string, exactly likesubstr()in Firefox. This behavior is observed in both Firefox and IE. - If
stopis negative: sets stop to:string.length – Math.abs(stop)(original value), except bounded at 0 (thus,Math.max(0, string.length + stop)) as covered in the ECMA specification.
Source: Rudimentary Art of Programming & Development: Javascript: substr() v.s. substring()