Welcome!

Kurt Cagle

Subscribe to Kurt Cagle: eMailAlertsEmail Alerts
Get Kurt Cagle via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Related Topics: RIA Developer's Journal, AJAX World RIA Conference

RIA & Ajax: Article

Real-World AJAX Book Preview: String Theory

Real-World AJAX Book Preview: String Theory

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs for the special pre-order price, click here for more information. Aimed at everyone from enterprise developers to self-taught scripters, Real-World AJAX: Secrets of the Masters is the perfect book for anyone who wants to start developing AJAX applications.

String Theory
Strings, like arrays, are objects, though because of their ubiquity and the way they're declared, it's sometimes easy to lose sight of this. Strings can be created either by using the String() object or via the single or double quotes:

var emptyStr = new String();
var redColor = 'red';
var blueColor = "blue";

Strings can also be constructed using the concat() method that joins individual strings together:

var trueColors = concat("red"," and ","blue");
print(trueColors);
=> 'red and blue'

However, because this operation is so common, the concat() method is usually deprecated in favor of the concat "+" operator, which will join the string after the plus sign with that before the plus sign:

print("red"+" and "+"blue");
'red and blue';

Similarly, strings can use the += operator to append the rvalue (the value on the right side of the equation) with the lvalue variable:

var buf = "red";
buf +=" and ";
buf +="blue";
print(buf);
=> 'red and blue'.

JavaScript strings follow the same conventions that Java and C++ do with regard to internal string delimiters. Double-quoted and single-quoted strings are indistinguishable in their efforts, and you can readily exchange between single quotes in double quotes and double quotes in single quotes.

However, there are times when you have to be able to encode additional information such as tabs, line feeds, or additional single or double quotes. You can use the backslash as an escape character, as shown in Table 2.1, to include invisible or problematic characters in strings.

So you can encode a double quote in a quoted string as follows:

var myQuote = "Sophi laughed,\"Of course, there's something to be said about escaping
from reality. I do it all the time.\""
print(myQuote);
=> Sophi laughed,"Of course, there's something to be said about escaping from reality.
I do it all the time."

Note that while most HTML elements are generally indifferent to white space issues (they normalize the white space, treating multiple contiguous spaces and carriage returns or new lines as single spaces), certain elements explicitly retain this information (such as the <PRE> presentation tag). As a consequence, the ability to manipulate such white space characters in JavaScript remains a high priority.

In most contemporary implementations, strings can be referenced using the array operators to retrieve the character at a given (zero-based) location:

print(blueStr[2]);
=> u

You can also retrieve pieces from a string using the substr()method, with the first argument giving the starting position of the string and the second (optional) argument giving the length of the substring:

print(blueColor.substr(2,2);
=> 'ue'

If the second argument isn't given, then the remainder of the string from the indicated character will be given:

print(blueColor.substr(1);
=> 'lue'

The substring() method is nearly identical to substr() save that it returns the string from the first index to the second index:

print(blueColor.substring(1,3);
=> 'lue'

The indexOf() and lastIndexOf() methods are useful for determining the location of a sub-string in another string. Applied as a method to a string, indexOf will return the 0-based index of the first occurrence of a sequence in the string, or -1 if the sequence isn't found:

print("violet".indexOf("let"));
=> 3
print("violet".indexOf("xyz"));
=> -1

The lastIndexOf() does the same thing but focuses on the last match in the string. For instance, to find the last "p" in purple, you'd use the method:

print("purple".indexOf("p"))
=> 0
print("purple".lastIndexOf("p"))
=> 3

For simple searches indexOf() is generally best, but if you're looking for more versatility in your searches, you're better off using the Regular Expressions discussed in the next section.

The toUpperCase() and toLowerCase() methods are sometimes useful for dealing with conversions, especially in file systems that are case-sensitive. They convert the full text of the string to upper or lower case, as appropriate.

Perhaps two of the most useful string/array functions are split() and join(). The split() method looks for a particular sub-string and splits the string before and after that string, then moves on to the latter result string and repeats the process again. When done, the result is returned as an array.

The split() method can be used to do a crude count for words in a paragraph by splitting the string on spaces:

var test = "This is a test. This is only a test.";
var testArr = test.split(" ");
print(testArr[0]);
=>this
print(testArr.length);
=> 9

Similarly, the join() method is actually an array method that takes all of the items in an array and joins them together using the string sequence provided as a parameter (or the blank string if nothing is supplied). For instance, if you had a collection of folders containing other folders or files as a list, you could readily convert this into a file path with JavaScript:

pathArr = ["http:","","www.mypath.com","images","myImage.jpg"]
var path = pathArr.join("/");
print(path);
=> http://www.mypath.com/images/myImage.jpg

The split() and join() methods can prove powerful in combination, especially since the split() method can take a Regular Expression as an argument as well as a string, which provides a good opportunity to segue into one of the more powerful aspects of JavaScript programming.

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs, click here to order.

More Stories By Kurt Cagle

Kurt Cagle is a developer and author, with nearly 20 books to his name and several dozen articles. He writes about Web technologies, open source, Java, and .NET programming issues. He has also worked with Microsoft and others to develop white papers on these technologies. He is the owner of Cagle Communications and a co-author of Real-World AJAX: Secrets of the Masters (SYS-CON books, 2006).

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.