Login Register

String Functions

Dojo includes some string operations. Here are a few examples:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Array Examples</title>
        <script type="text/javascript"
                    src="http://o.aolcdn.com/dojo/1.0.0/dojo/dojo.xd.js">
</script>
        <script type="text/javascript">
           dojo.require("dojo.string");
          
       dojo.addOnLoad(function(){
           // Pads * onto the left hand side
           console.debug(dojo.string.pad("9.99",10,"*"));
           
           // With true on the end, pads on the right
           console.debug(dojo.string.pad("Ninety-Nine and 75/100",25,"-",true));
           
           // Dojo has two versions of trim, functionally equivalent.  The first
           // is in base so you don't have to dojo.require anything.
           console.debug("[" + dojo.trim("    spaced    ") + "]");
           
           // The second is dojo.string you need to dojo.require("dojo.string"), but
           // it's faster.
           console.debug("[" + dojo.string.trim("    spaced    ") + "]");
           
           // Substitute does simple ${var} template substitution, much like you see in
           // _Templated widgets.  You can use it with arrays:
           console.debug(
               dojo.string.substitute(
                   "${2}ft ${0} cable - ${1}",
                   [ "red", "fiber", 7]
               )
           );
           
           // Or, even better, with objects:
           console.debug(
               dojo.string.substitute(
                   "${length}ft ${color} cable - ${media}",
                   {color: "red", media: "fiber", length: 7}
               )
           );
           
           // Even nested objects, using dot notation
           console.debug(
               dojo.string.substitute(
                   "Ooops, spilled ${condiment.ketchup}",
                   {burger: "boca",
                       condiment: { ketchup: "heinz", mustard: "french's"},
                    bun: "wonder"}
              )
           );
       });
   </script>
</head>
</html>

Is it possible to modify the

Is it possible to modify the dojo.string.substitute() method to not perform a substitution if the property is not defined?

e.g.

dojo.string.substitute("${x},${y},${z}",{x:1,y:2})// --> "1,2,${z}"

Currently, it just causes a JavaScript error saying "value has no properties".

It looks like the method could be change from this...

return template.replace(/\$\{([^\s\:\}]+)(?:\:([^\s\:\}]+))?\}/g, function(match, key, format){
var value = dojo.getObject(key,false,map);
...
return value.toString();

...to this...

return template.replace(/(\$\{([^\s\:\}]+)(?:\:([^\s\:\}]+))?\})/g, function(orig, match, key, format){
var value = dojo.getObject(key,false,map);
if (! value) return orig;
...
return value.toString();