Use str.slice(..)

By Luke Smith on October 10, 2008 10:05 AM

There are three ways to get a substring from a string in JavaScript:

  1. str.substr(startIndex,length)
  2. str.substring(startIndex,endIndexPlusOne)
  3. str.slice(startIndex,endIndexPlusOne)

substr and substring

All browsers treat str.substring(-2) as str.substring(0).

substring(4,2) inputs are automatically reversed when the second param is less than the first, resulting in substring(2,4). So substring(12,-2) is treated as substring(0,12).

IE treats str.substr(-2) as str.substr(0). All others support neg index in substr.

All browsers support str.slice(-2).

slice is the only method that properly handles negative indexes across all browsers. Here's a demo, run in your current browser.

Starting string: var str = "abcdefghijklmnopqrstuvwxyz"

coderesultdesiredcorrect?

Note if you are viewing this in IE, str.substr(-12,5) results in "abcde", whereas in other browsers "opqrs".

So in conclusion, there are too many ways to skin the substring cat. substr has cross-browser compatibility issues and substring doesn't support negative indexes. slice is always safe, so just use slice.

Your comment?

HTML is ok

No TrackBacks (http://lucassmith.name/mt/mt-tb.cgi/111)

ls.n

LucasSmith.name

Luke and Liam

I'm Luke. I am a front end engineer at Yahoo! on the YUI team.

Mostly I write about code stuff, but occassionally I'll mix in some real life. You've been warned.

Archives

Tags

Feeds

Subscribe to feed Recent entries

Content licensed under Creative Commons

Code licensed under BSD license

©2005 - 2010 Lucas Smith

Powered by Movable Type