Skip to content

Instantly share code, notes, and snippets.

@wadackel
Last active August 29, 2015 14:25
Show Gist options
  • Save wadackel/7d89c7bc69f90acebd06 to your computer and use it in GitHub Desktop.
Save wadackel/7d89c7bc69f90acebd06 to your computer and use it in GitHub Desktop.
シンプルなtemplate関数2種類
/**
* ================================================
* シンプルに
* ================================================
*/
/**
* テンプレート文字列を展開
*
* @param string:String テンプレート文字列
* @param values:Object 展開する値
* @return String
*/
function template(string, values){
return string.replace(/\$\{(.*?)\}/g, function(all, key){
return Object.prototype.hasOwnProperty.call(values, key) ? values[key] : "";
});
}
// test
console.log(template("My name is ${name} ${hoge}", {name: "Bob"})); // => My name is Bob
/**
* ================================================
* 形式を指定出来るように
* ================================================
*/
/**
* 文字列を正規表現用にエスケープ
* @see http://phpjs.org/functions/preg_quote/
*/
function preg_quote(str, delimiter) {
return String(str).replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
}
/**
* テンプレート文字列を展開
*
* @param string:String テンプレート文字列
* @param values:Object 展開する値
* @param before:String("${") テンプレートの開始文字
* @param after:String("}") 終了文字
* @return String
*/
function template(string, values, before, after){
before = preg_quote(before || "${");
after = preg_quote(after || "}");
return string.replace(new RegExp(before + "(.*?)" + after, "g"), function(all, key){
return Object.prototype.hasOwnProperty.call(values, key) ? values[key] : "";
});
}
// test
console.log(template("My name is ${name} ${hoge}", {name: "Bob"})); // => My name is Bob
console.log(template("My name is %name% %hoge%", {name: "Bob"}, "%", "%")); // => My name is Bob
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment