July 12, 2007 § 16 Comments
substr() method extracts a specified number of characters in a string, from a start index.
Syntax: string.substr(start, length);
substring() method extracts the chars in a string between two specified indexes.
Syntax: string.substring(start, stop);
Quick Notes aout Substr:
- If start is negative, Internet Explorer returns the whole string. That’s wrong! IE should use the last character in the string.
Quick Notes about 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 string’s length, either argument will use string’s length.
- If start > stop, then substring will swap those 2 arguments.
UPDATE (Added Slice upon request)
slice() works like substring() with a few different behaviors.
Syntax: string.slice(start, stop);
Quick Notes about Slice:
- If stop is omitted, slice extracted 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).
- Mozilla Developer Documentation – substr()
- Mozilla Developer Documentation – substring()
- Mozilla Developer Documentation – slice()
- MSDN Documentation – substr()
- MSDN Documentation – substring()
- MSDN Documentation – slice()