JavaScript has two built in methods that are very similar in name and function- substring() and substr(). Developers and designers who also use server side languages may find it easy to mix them up, since methods like these have similar names across other languages. Either way, mixing them up might cause bugs with your scripts. For example, see the snippet below that looks almost identical, but yields different results.

JAVASCRIPTview code
var string = 'hello world of scripting';
 
var newstr = string.substring(6,11);
// results in 'world';
 
var newstr = string.substr(6,11);
// results in 'world of sc'

Solid Tip: Remember that the first character in a string is always 0 and the second character is 1.

The difference lies in the second parameter.
For substring(), the second parameter is the stopping point (character 11).
For substr(), the second parameter is the length (11 characters long)

The first parameter is the starting point in both functions. Obviously, that is required. The second parameter is optional for both. If you enter only the first parameter, then both functions will behave the same way and go to the end of the string.

Historically, substring() was the method of choice because substr() did not use to be cross-browser friendly. However, that was in the days of Netscape, and IE3. Today, substr() works in every browser.

Solid Tip: Most developers and designers who use scripting like this are also involved with a server side language. Choose your JavaScript version based on that. If you use PHP, use substr(). If you use Java or ASP, they both use substring().

Pitfalls to Watch Out For

Substring() is forgiving with mistakes, so watch out. It will automatically swap the two parameters if the second is larger than the first and you might not even know you had them backwards.

Both functions will accept parameters that are not numbers. These will be converted into 0 if they cannot be parsed as integers Therefore, ‘xyz’ is treated as 0 and ‘7’ is treated as 7. While this may seem helpful, incorrect type (integer vs string) is a big source of bugs.

Substr() can take a negative start parameter to start from the end of a string, but do not let yourself be tempted. This usage, even in the year 2010, is not supported by Internet Explorer (ya, shocker I know). Avoid using negative numbers.