Active Server - Learn The Difference Between JavaScript's substr() and substring() Functions (Microsoft Scripting Edition 5.0+)


It's safe to say that manipulating strings is a critical aspect to learn when using JavaScript. You'll discover all kinds of reasons for doing so, and to this end, JavaScript contains a host of helpful functions to help you along the way.


When you do need to manipulate a string--specifically, when you need to extract a portion of a string from a larger one--keep in mind that JavaScript offers the standard substring() function as well as a newer (relatively) substr() method.


With both these functions, you provide a starting index number. This number tells JavaScript at which character to start the new snippet. However, the new string WILL NOT actually include the character at the starting index.


For the substring() method, you also supply a second ending index number. With this number in place, JavaScript extracts the range of characters from the starting to ending index. For instance, given the following code:


  • var str = new String("JavaScript")
  • var newStr = str.substring(4,10)
  • alert(newStr)
  • The message box would display the string "Script"

Unlike substring(), the substr() function's second argument is optional. In this argument, you enter a number that indicates the length of the desired snippet. With this in mind, to generate the same results as our previous code using this method, we'd use:


  • var str = new String("JavaScript")
  • var newStr = str.substring(4,6)
  • alert(newStr)

Go back