3.9. Getting Parts of a String

Switching back and forth between languages can have its pitfalls. There may be something slightly different between the two that continues to trip you up. Accessing parts of a string is a common programming task and one that may trip you up as you go back and forth from JavaScript to C# or Visual Basic.

The substr() function for extracting part of a string is used in C and C++, while the Substring() method is supported in C# and Visual Basic. They are both available in JavaScript. They all operate on 0-based strings. If you are also using Visual Basic, which is 1-based, this may be an initial obstacle.

Both substr() and Substring() have versions that accept a single argument and return the remainder of the string starting at that index. The two argument versions behave slightly differently. The substr() function takes a start index and the number of characters to extract. The Substring() function takes a start index and an end index. In isolation, this seems straightforward, but you will undoubtedly be coding in something other than JavaScript part of the time and may find yourself scratching your head trying to remember which language supports which version. JavaScript has them both. Listing 3-25 utilizes both functions.

Example 3-25. Utilizing both substr() and substring()
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Substrings</title>

    <script type="text/javascript">
        var aString = "0123456789";
document.write(aString.substr(2) + "<br ...

Get Professional ASP.NET 3.5 AJAX now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.