Pages

Saturday, March 10, 2012

Slice & Substring (JavaScript)

Okay, this time I put this article in English, because it's more straightforward than translating to Indonesian language.

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 the string's length, either argument will use the string's length.
  • If start > stop, then substring will swap those 2 arguments.
Notes on slice():
  • If stop is omitted, slice extracts 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).
For  .substr() and .slice(), they are notably different!

.slice() is:
string.slice(beginIndex, endIndex)

Whereas .substr() is:
string.substr(beginIndex, length);
 
So for example, if we have "1234" and wanted "23", it would be:
"1234".slice(1,3)
//or...
"1234".substr(1,2)
 
They also have different behavior for the more-rarely used negative indexes, look at the MDC documentation for .slice() and .substr() for full descriptions.

Source: StackOverflow

No comments:

Post a Comment