String prototype substrReplace function str2 offset len return this su

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
String.prototype.substrReplace = function (str2, offset, len) {
return this.substring(0, offset) + str2 + this.substring(offset + len);
}
Function.prototype.text = function () {
var v = this.toString(), start = v.indexOf('{/*') + 3, end = v.lastIndexOf('*/}');
return v.substr(start, end - start);
};
String.prototype.tpl = function (params) {
var m, var_re = /\{\{\s*([\w\d-_\$]+)\s*\}\}/gim, offset = 0, out = this;
while (m = var_re.exec(out)) {
var value = params[m[1]] || "";
out = out.substrReplace(value, m.index + offset, m[0].length);
var_re.lastIndex = m.index + value.length;
}
return out;
};
var text = (function () {/*
<a href="{{link_url}}">
<img src="{{img_url}}" />
</a>
*/}).text().tpl({
link_url: "http://spaces.ru",
img_url: "http://spaces.ru/i/lol.gif"
});
console.log(text);