Skip to content

Instantly share code, notes, and snippets.

@maliubiao
Last active August 29, 2015 14:02
Show Gist options
  • Save maliubiao/8fd85c64b62919b6a48d to your computer and use it in GitHub Desktop.
Save maliubiao/8fd85c64b62919b6a48d to your computer and use it in GitHub Desktop.
string_format.js
/*
* {% ABC %}
*
*/
function string_format(format, context) {
if ((typeof format != "string") ||
(typeof context != "object")) {
return;
}
var result = [];
var qs = 0;
var init = 0;
var tlen = format.length;
var i = 0;
while(i < tlen) {
if ((format[i] == "{") && (format[i+1] == "%")) {
//tag start
qs = 1;
//valid tag location
init = i + 2;
//skip {
i = i + 1;
//ignore until qs 2
}
if ((format[i] == "%") && (format[i+1] == "}")) {
qs = 2;
//close quote, fallthrough
}
if (qs == 0) {
//normal character
result.push(format[i]);
} else if (qs == 2) {
//close quote, insert context
var tag = format.slice(init, i).trim(" ");
result.push(context[tag]);
qs = 0;
//skip %
i = i + 1;
}
//skip % or { or add index
i = i + 1;
}
return result.join("");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment