String Utilities

Trimming any existing whitespace from a string is an increasingly common operation. The next time you need to do this, use Base's trim function instead of writing your own.

Tip

There can be subtle performance issues with even the seemingly most trivial utility functions, and using the toolkit provides you with the benefits and collective knowledge of a community that has given careful consideration to such issues.

Here's an example of trim at work:

var s = "  this is a value with whitespace padding each side    ";
s = dojo.trim(s); //"this is a value with whitespace padding each side"

Core's string module also includes a few other useful string functions. Each of these examples assumes that you have already fetched the dojo.string module via a dojo.require statement.

dojo.string.pad

Pads a string value and guarantees that it will exactly fill a particular number of characters. By default, padding fills in on the left. An optional parameter causes padding to fill in from the right:

dojo.string.pad("", 5); // "00000"
dojo.string.pad("", 5, " "); // "     "
dojo.string.pad("0", 5, "1"); // "11110"
dojo.string.pad("0", 5, "1", true); // "01111"
dojo.string.substitute

Provides parameterized substitution on a string, optionally allowing a transform function and/or another object to supply context:

//Returns "Jack and Jill went up a hill."
dojo.string.substitute("${0} and ${1} went up a hill.", ["Jack", "Jill"]);

//Returns "Jack and Jill went up a hill."
dojo.string.substitute("${person1} and ${person2} went up a hill.", {person1
: "Jack", person2: "Jill"});
//"*Jack* and *Jill* went up a hill."
dojo.string.substitute("${0} and ${1} went up a hill.", ["Jack", "Jill"],
function(x) {
  return "*"+x+"*";
});
dojo.string.trim

At the cost of a little more size than Base's implementation, Core's string module provides a slightly more efficient version of trim that can be used when performance really matters:

dojo.string.trim( /* your string value */);

Get Dojo: The Definitive Guide 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.