What's New in Prototype 1.5?
by Scott Raymond
|
Pages: 1, 2, 3, 4, 5
String Extensions
In a typical web application, a great deal of code is written to simply manipulate strings. Thus, a thorough set of string-processing methods are an invaluable weapon in the web developer's arsenal. With version 1.5, Prototype's suite of extensions to the standard String class (or more accurately, the String prototype) has roughly doubled. Here are the latest additions.
-
strip()removes leading and trailing whitespace from a string. For example:" foo ".strip(); // => "foo" -
gsub(pattern, replacement)returns the result of replacing all occurrences of pattern (either a string or regular expression) with replacement, which can be a string, a function, or aTemplatestring (see theTemplateclass below). If replacement is a function, it's passed an array of matches. Index zero of the array contains the entire match; subsequent indexes correspond to parenthesized groups in the pattern. For example:"In all things will I obey".gsub("all", "ALL"); // => "In ALL things will I obey"
"In all things will I obey".gsub(/[aeiou]/i, "_"); // => "_n _ll th_ngs w_ll _ _b_y"
"In all things will I obey".gsub(/[aeiou]/i, function(x){ return x[0].toUpperCase(); }); // => "In All thIngs wIll I ObEy"
'Sam Stephenson'.gsub(/(\w+) (\w+)/, '#{2}, #{1}'); // => "Stephenson, Sam" -
sub(pattern, replacement[, count])is identical togsub(), but takes an optional third argument specifying the number of matches that will be replaced, defaulting to one. For example:"In all things will I obey".sub(/[aeiou]/i, "_"); // => "_n all things will I obey"
"In all things will I obey".gsub(/[aeiou]/i, "_", 3); // => "_n _ll th_ngs will I obey"
'Sam Stephenson'.sub(/(\w+) (\w+)/, '#{2}, #{1}'); // => "Stephenson, Sam" -
scan(pattern, iterator)finds all occurrences of pattern and passes each to the function iterator. For example:// Logs each vowel to the console
"Prototype".scan(/[aeiou]/, function(match){ console.log(match); }) -
truncate([length[, truncation]])trims the string length characters (default is 30) and appends the string truncation, if needed (default is "..."). For example:"Four score and seven years ago our fathers brought".truncate(); // => "Four score and seven years ..."
"Four score and seven years ago our fathers brought".truncate(20); // => "Four score and se..."
"Four score and seven years ago our fathers brought".truncate(30, ' (read more)'); // => "Four score and sev (read more)" -
capitalize()returns a string with the first character in uppercase. For example:"prototype".capitalize(); // => "Prototype" -
dasherize()replaces underscores with dashes. For example:"hello_world".dasherize(); // => "hello-world"
"Hello_World".dasherize(); // => "Hello-World" -
underscore()replaces"::"s with"/"s, convertsCamelCasetocamel_case, replaces dashes with underscores, and shifts everything to lowercase. For example:"Foo::Bar".underscore(); // => "foo/bar"
"borderBottomWidth".underscore(); // => "border_bottom_width" -
succ()returns the"next"string, allowing forStringranges. For example:"abcd".succ(); // => "abce"
$R('a','d').map(function(char){ return char; }); // => ['a','b','c','d']
In addition to Prototype's new extensions to the String prototype, it also defines an entirely new class for string manipulation: Template, which provides simple templating functionality with JavaScript strings. Using the Template class is simple: just instantiate a new template with the constructor, and then call evaluate on the instance, providing the data to be interpolated. For example:
var row = new Template('<tr><td>#{name}</td><td>#{age}</td></tr>');
To render a template, call evaluate on it, passing an object containing the needed data. For example:
var person = { name: 'Sam', age: 21 };
row.evaluate(person); // => '<tr><td>Sam</td><td>21</td></tr>'
row.evaluate({})); // => '<tr><td></td><td></td></tr>'
The default template syntax mimics Ruby's style of variable interpolation (e.g., #{age}). To override this behavior, provide a regular expression as the second argument to the constructor. For example:
// Using a custom pattern mimicking PHP syntax
Template.PhpPattern = /(^|.|\r|\n)(<\?=\s*\$(.*?)\s*\?>)/;
var row = new Template('<tr><td><?= $name ?></td><td><?= $age ?></td></tr>', Template.PhpPattern);
row.evaluate({ name: 'Sam', age: 21 }); // "<tr><td>Sam</td><td>21</td></tr>"
Templates are especially powerful in combination with Prototype's capability to insert content into the DOM. For example:
// <table id="people" border="1"></table>
var row = new Template('<tr><td>#{name}</td><td>#{age}</td></tr>');
var people = [{name: 'Sam', age: 21}, {name: 'Marcel', age: 27}];
people.each(function(person){
new Insertion.Bottom('people', row.evaluate(person));
});