-
-
Save roboncode/bac91b42989ce9880819 to your computer and use it in GitHub Desktop.
supplant - Crockford
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* supplant() does variable substitution on the string. It scans through the string looking for | |
* expressions enclosed in { } braces. If an expression is found, use it as a key on the object, | |
* and if the key has a string value or number value, it is substituted for the bracket expression | |
* and it repeats. | |
* | |
* Updated by Rob Taylor | |
* http://roboncode.com | |
* | |
* Originally written by Douglas Crockford | |
* http://www.crockford.com/ | |
*/ | |
String.prototype.supplant = function (o, options) { | |
var openTag = options ? options.openTag || '{' : '{'; | |
var closeTag = options ? options.closeTag || '}' : '}'; | |
return this.replace( | |
new RegExp(openTag + '([^' + openTag + closeTag + ']*)' + closeTag, 'g'), | |
function (a, b) { | |
var r = o[b]; | |
return typeof r === 'string' || typeof r === 'number' ? r : a; | |
} | |
); | |
}; | |
function supplant (str, o, options) { | |
var openTag = options ? options.openTag || '{' : '{'; | |
var closeTag = options ? options.closeTag || '}' : '}'; | |
return str.replace( | |
new RegExp(openTag + '([^' + openTag + closeTag + ']*)' + closeTag, 'g'), | |
function (a, b) { | |
var r = o[b]; | |
return typeof r === 'string' || typeof r === 'number' ? r : a; | |
} | |
); | |
} | |
// | |
// Example 1 basic usage | |
// | |
linkTpl = '<a href="{url}" class="{class}">{lable}</a>'; | |
links = linkTpl.supplant({ | |
url : 'http://example.com', | |
class : 'lnk', | |
lable : 'Link Bezeichnung' | |
}); | |
// | |
// Example 2 more advanced usage | |
// | |
var items = [], | |
listItemTpl = '<li><a href="{url}" class="{class}">{lable}</a></li>'; | |
for (i=0;i<20;i++) { | |
items.push(listItemTpl.supplant({ | |
url : 'http://example.com', | |
class : 'lnk', | |
lable : 'Link Bezeichnung' | |
})); | |
} | |
// Join items e.g. to insert into DOM | |
items = items.join(''); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment