PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Eight Weeks of Prototype: Week 3, Prototype Data Types

The String Object

The first data type we will look at is the String object. Prototype extends this object to give you a wider range of methods that can be called on strings. Each of these methods is documented on the Prototype web site at http://prototypejs.org/api/string.

Each of these methods can be applied directly to a string literal, or to variables that hold strings. For instance, one of the functions made available is strip(), used to remove whitespace before and after a string (just as the PHP function trim() works). Listing 1 shows two different ways you can use this method. The first way in this example is to call strip() directly on a variable, while the second way is to apply strip() directly to a literal string.

Listing 1 The different ways to apply string functions (listing-1.html)
<html>
    <head>
        <title>Two different ways of applying string methods</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            var string = ' test ';
            var result = string.strip();
            // result holds the string 'test'
 
            var result = ' test '.strip();
            // result holds the string 'test'
        </script>
    </body>
</html>

Rather than covering every method available, I'll cover a few basic ones to begin with, and then give you an idea of some other useful string functions that are available when using Prototype.

String Testing

The first functions we will look at are for string testing. That is, each method returns a Boolean value (true or false). Several examples of using each of the methods covered here are shown in Listing 2.

Firstly, the empty() method. This method returns true if the target string has zero-length. An alternative to using this method is to use the expression myVar.length == 0.

Next, the blank() method. This method returns true if the target string has no characters or contains only whitespace. Be aware that line feeds are treated as whitespace. The alternative to using this method is to combine the strip() and empty() methods we have already looked at. That is, myVar.blank() will return the same value as myVar.strip().empty().

Now we will look at the include() method. Although the name is slightly misleading, this method checks whether or not a string contains an instance of another string. You can use regular expressions as an alternative to this method, although for a simple test this method will work fine. For instance, if (myVar.include('bar') { ... } will work the same as if (/bar/.test(myVar)) { ... }.

Similar to include() are the startsWith() and endsWith() methods. Rather than searching for a substring anywhere in the string, the substring must occur at the beginning or end of the string respectively. Once again you can use regular expressions to achieve this functionality. In the case of startsWith(), you would use the ^ symbol at the start of the regular expression (to signify the match must occur at the start of the string), while you would use the $ symbol to match at the end of the string. For example, if (myVar.endsWith('foo')) { ... } will function the same as if (/foo$/.test(myVar)) { ... }).

Listing 2 Using the blank(), empty(), include() and endsWith() methods (listing-2.html)
<html>
    <head>
        <title>Using the blank(), empty(), include() and endsWith() methods</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            var string = '';
            // string.empty() returns true
 
            var string = '  ';
            // string.empty() returns false
            // string.strip().empty() returns true
 
            var string = '  ';
            // string.blank() returns true
 
            var string = 'foo';
            // string.blank() returns false
 
            var string = '';
            // string.blank() returns true
 
            var string = '\n';
            // string.blank() returns true
 
            var string = 'The quick brown fox';
 
            if (string.include('fox'))
                alert('The string contains fox!');
 
            if (!string.endsWith('.'))
                string += '.';
 
            alert(string);
        </script>
    </body>
</html>

Other Useful String Methods

Some other string methods that you may find useful are listed below. For full documentation on each of these, refer to the Prototype API guide for strings at http://prototypejs.org/api/string.

  • isJSON() - Check whether a string contains syntactically correct JSON data
  • camelize() - Turn a dash-separated string into camel-caps. This is useful for translating CSS properties into their DOM equivalent. For instance, 'background-color'.camelize() returns backgroundColor.
  • capitalize() - This method formats a string so the first letter of each word is a capital while the rest of the letters are lower case. This is the equivalent of using ucwords(strtolower($str)) in PHP.
  • escapeHTML() - This method converts certain characters into their correct HTML entities. For instance, '&lgt;'.escapeHTML() would return the string &lt;.
  • toQueryParams() - Parse the query string from a URL into an object of key/value pairs. This is similar to the PHP parse_str() function, and will result in data similar to that of the PHP's $_GET superglobal.
  • truncate() - Shorten a string to a specified length and append a suffix to it. This is useful when you want to show only a partial string but want to indicate there is more to it. For example, 'The Quick Brown Fox'.truncate(12, '...') would return The Quick....
Note: This is similar to the truncate modifier in the Smarty Template Engine, except that Smarty also has the option to append the suffix without breaking up a word, whereas this method does not.

There are many more string functions available, so you should read over the Prototype documentation to find out more about them.

In This Article