Does anyone know what the difference is between these two methods?
String.prototype.slice
String.prototype.substring
Does anyone know what the difference is between these two methods?
String.prototype.slice
String.prototype.substring
slice() works like substring() with a few different behaviors.
Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);
What they have in common:
start equals stop: returns an empty stringstop is omitted: extracts characters to the end of the stringDistinctions of substring():
start > stop, then substring will swap those 2 arguments.NaN, it is treated as if it were 0.Distinctions of slice():
start > stop, slice() will return the empty string. ("")start is negative: sets char from the end of string, exactly like substr() in Firefox. This behavior is observed in both Firefox and IE.stop is 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()
substr: It's providing us to fetch part of the string based on specified index. syntax of substr- string.substr(start,end) start - start index tells where the fetching start. end - end index tells upto where string fetches. It's optional.
slice: It's providing to fetch part of the string based on the specified index. It's allows us to specify positive and index. syntax of slice - string.slice(start,end) start - start index tells where the fetching start.It's end - end index tells upto where string fetches. It's optional. In 'splice' both start and end index helps to take positive and negative index.
sample code for 'slice' in string
var str="Javascript";
console.log(str.slice(-5,-1));
output: crip
sample code for 'substring' in string
var str="Javascript";
console.log(str.substring(1,5));
output: avas
[*Note: negative indexing starts at the end of the string.]