Difference between slice() and substring() in javascript - Java @ Desk

Thursday, August 8, 2013

Difference between slice() and substring() in javascript

Difference between slice() and substring() in javascript

slice() works like substring() works the same way for string in javascript.

var stringVar = "slice_vs_substring";
stringVar.slice(start, stop);
stringVar.substring(start, stop);

substring():

start==stop: It returns an empty string.
if(start==stop){ 
 return ""
}


only start index, stringVar.substring(index): It returns string from [index+1] till length of string
stringVar.substring(3) -> return "ce_vs_substring";

start > stop, stringVar.substring(10 , 0): It returns stringVar.substring(0, 10)
If start > stop, then substring will swap those 2 arguments.
stringVar.substring(10, 0) -> return "slice_vs_s";

start > LENGTH OR stop > LENGTH, stringVar.substring(0 , 40): It returns stringVar.substring(0, LENGTH)
If either argument is greater than the string's length, either argument will use the string's length.
stringVar.substring(0 , 40) -> return "slice_vs_substring";

start < 0 OR stop < 0, stringVar.substring(-10 , 4): It returns stringVar.substring(0, 4)
If either argument is less than 0 or is NaN, it is treated as if it were 0.
stringVar.substring(-10 , 4) -> return "slic";


var stringVar = "slice_vs_substring";
stringVar.slice(start, stop);
stringVar.substring(start, stop);

slice():

start==stop: It returns an empty string.
if(start==stop){ 
 return ""
}

only start index, stringVar.slice(index): It returns string from [index+1] till length of string
stringVar.slice(3) -> return "ce_vs_substring";

start > stop, stringVar.slice(1 , 4): It returns stringVar.slice(1, 4), i.e. from index position 1 till index position 3
If start > stop, then slice will swap those 2 arguments.
stringVar.slice(1, 4) -> return "lic";

start > LENGTH OR stop > LENGTH, stringVar.slice(0 , 40): It returns stringVar.substring(0, LENGTH)
If either argument is greater than the string's length, either argument will use the string's length.
stringVar.slice(0 , 40) -> return "slice_vs_substring";

stop < 0, stringVar.slice(0 , -4): It returns stringVar.substring(0, [(LENGTH -1) - Match.abs(-4))
If stop is negative, slice() will set stop to: (string.length – 1) – Math.abs(stop)
stringVar.slice(0 , -4) -> return "slice_vs_subst";







No comments:

Post a Comment