Jump to content

Strings: Substr()&slice() What's The Different?


Athlon

Recommended Posts

substr() selects from a start point and a given length. slice() selects between a start point and an end point.The two methods that are identical are slice() and substring(). Though they have performance differences, I did tests a long time ago with them. Since a string is technically an array of characters, the slice() method may have been inherited from the array properties.

Link to comment
Share on other sites

"Semantically," they seem to be the same, but applied to different kind of data (just to explain it in some way) according tohttp://www.w3schools.com/jsref/jsref_substring.aspandhttp://www.w3schools.com/jsref/jsref_slice_array.aspLook at the example ("adapted" from that in the latter link)

<html><body>  <h1>Hi!</h1>  <script type="text/javascript">	var arrayVar = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];	document.write(arrayVar.slice(0,1) + "<br />");	document.write(arrayVar.slice(1) + "<br />");	document.write(arrayVar.slice(-2) + "<br />");	document.write(arrayVar + "<br />");	var stringVar = "0123456789"	document.write(stringVar.slice(0,1) + "<br />");	document.write(stringVar.slice(1) + "<br />");	document.write(stringVar.slice(-2) + "<br />");	document.write(stringVar + "<br/>");  </script></body><html>

i.e. if slice is applied to an array returns an array (as I think it should be used), and if slice is applied to a string it returns a string (I think in some way it's applied some sort of cast... but I'm not sure). Substring can only be applied to a string and returns a string.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...