2
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
3
Code licensed under the BSD License:
4
http://developer.yahoo.net/yui/license.txt
8
* String variable substitution and string formatting.
9
* If included, the substitute method is added to the YUI instance.
13
YUI.add("substitute", function(Y) {
15
var L = Y.Lang, DUMP='dump', SPACE=' ', LBRACE='{', RBRACE='}',
18
* The following methods are added to the YUI instance
19
* @class YUI~substitute
23
* Does variable substitution on a string. It scans through the string
24
* looking for expressions enclosed in { } braces. If an expression
25
* is found, it is used a key on the object. If there is a space in
26
* the key, the first word is used for the key and the rest is provided
27
* to an optional function to be used to programatically determine the
28
* value (the extra information might be used for this decision). If
29
* the value for the key in the object, or what is returned from the
30
* function has a string value, number value, or object value, it is
31
* substituted for the bracket expression and it repeats. If this
32
* value is an object, it uses the Object's toString() if this has
33
* been overridden, otherwise it does a shallow dump of the key/value
34
* pairs if Y.dump is available (if dump isn't available, toString()
37
* This method is included in the 'substitute' module. It is not included
42
* @param s {string} The string that will be modified.
43
* @param o An object containing the replacement values
44
* @param f {function} An optional function that can be used to
45
* process each match. It receives the key,
46
* value, and any extra metadata included with
47
* the key inside of the braces.
48
* @return {string} the substituted string
50
substitute = function (s, o, f) {
51
var i, j, k, key, v, meta, saved=[], token;
54
i = s.lastIndexOf(LBRACE);
58
j = s.indexOf(RBRACE, i);
63
//Extract key and meta info
64
token = s.substring(i + 1, j);
67
k = key.indexOf(SPACE);
69
meta = key.substring(k + 1);
70
key = key.substring(0, k);
76
// if a substitution function was provided, execute it
86
v = Y.dump(v, parseInt(meta, 10));
90
// look for the keyword 'dump', if found force obj dump
91
var dump = meta.indexOf(DUMP);
93
meta = meta.substring(4);
96
// use the toString if it is not the Object toString
97
// and the 'dump' meta info was not found
98
if (v.toString===Object.prototype.toString||dump>-1) {
99
v = Y.dump(v, parseInt(meta, 10));
105
} else if (!L.isString(v) && !L.isNumber(v)) {
106
// This {block} has no replace string. Save it for later.
107
v = "~-" + saved.length + "-~";
108
saved[saved.length] = token;
113
s = s.substring(0, i) + v + s.substring(j + 1);
118
// restore saved {block}s
119
for (i=saved.length-1; i>=0; i=i-1) {
120
s = s.replace(new RegExp("~-" + i + "-~"), "{" + saved[i] + "}", "g");
127
Y.substitute = substitute;
128
L.substitute = substitute;