slice()
works like substring()
with a few different behaviors.Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);
Notes on substring()
:- If
start
equalsstop
, 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 isNaN
, it is treated as if it were0
. - If either argument is greater than the string's length, either argument will use the string's length.
- If
start > stop
, thensubstring
will swap those 2 arguments.
slice()
:- If
stop
is omitted,slice
extracts chars to the end of the string, exactly likesubstring()
. - If
start > stop
,slice()
will NOT swap the 2 arguments. - If
start
is negative,slice()
will set char from the end of string, exactly likesubstr()
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 .
Whereas
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