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.padPads 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.substituteProvides 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} ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access