From the mind of Kon Pik…

Hopeless without the internet

Cross-Browser Javascript String Functions: substr, substring, or splice?

Recently I had to do some relatively simple string manipulations. I’ve always been taught to use the .substring method in all the languages I’ve ever used. Javascript actually offers several different approaches. So while I did not have to do anything computationally intensive, I was curious as to which of the following methods actually performed the fastest in different browsers as all the same functionality is available with these out-of-box approaches.

We have the slice(), substr() and substring() methods. To be complete, the function’s behavior is described below (for detailed info read the W3 docs).

string slice(startIndex, endIndex)
The slice method takes in a start index and an end index and returns the values in between those indexes.
Assertions: startIndex is 0-based, endIndex > startIndex.  Note that endIndex can be negative, but backwards compatibility is not in-scope


string substr(startIndex, length)
The substr method takes in a start index and an integer denoting how many characters to take from the startIndex parameter.
Assertions: startIndex is 0-based, length >= 0


string substring(startIndex, endIndex)
The substring method takes in a start index and an endIndex. This re-traverses the string in order to get the substring.
Assertions: startIndex is 0-based


Please Note!
I am not covering the full range of parameters (e.g. slice method can have endIndex > startIndex, but this depends on browser implementation). Some (mostly older IE) browsers handle these cases in unexpected ways, so they will not be discussed here.

Not going to lie, I got distracted into creating some pseudo-alert-boxes that you see above you. Pretty, aren’t they?

In any case, I wrote some simple scripts that loop through a string and call each of these, for short, medium, and long strings.

I validated the following test scenarios:

  • Access 1 character in a string using substr
  • Access 1 character in a string using slice
  • Access 1 character in a string using substring

At the time of writing, the results are as follows

One thing to note is that when I tested this, I tested IE7 and IE8 by running IE9 in downgraded browser mode – therefore the results are not accurate for IE7 and IE8 for sure. As noted in the comments, Fennec 10 is Firefox Beta 10 (Android) and Android 2.3.7 is the default Android browser. The Android device that these tests were ran on is the Nexus S 4G.

Please feel free to run them yourself and see what you end up with.

JSPerf Links

if you are using Chrome then use substr
if you are using Default Android Browser then use slice
if you are using Firefox Beta (Android) then use substring
if you are using Firefox 9 (Windows) then use substr
if you are using IE9 then use substr or substring

Tags: , , , , , , ,