Javascript: substr() v.s. substring()

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).



§ 16 Responses to Javascript: substr() v.s. substring()

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

What’s this?

You are currently reading Javascript: substr() v.s. substring() at RAPD.


%d bloggers like this: